My code is passing a JavaScript object to a function implemented in C++. The C++ code needs to validate the type of each property and supply a default value if either the property is missing or the type is wrong.
The following code seems to work (only showing the integer case) but I'm wondering if there is a more straightforward way to handle this. I'm by no means an expert in this area so all suggestions for improvements are welcome.
int get_integer(
v8::Local<v8::Object> obj,
v8::Local<v8::String> prop,
int default_value = 0) {
if (Nan::Has(obj, prop).FromMaybe(false)) {
Nan::MaybeLocal<v8::Value> v = Nan::Get(obj, prop);
if (!v.IsEmpty()) {
v8::Local<v8::Value> val = v.ToLocalChecked();
if (val->IsInt32() || val->IsNumber()) {
return val->IntegerValue();
}
}
}
return default_value;
}
It's called by code similar to the following:
v8::Local<v8::Object> obj = info[0]->ToObject();
v8::Local<v8::String> prop = Nan::New<v8::String>("prop").ToLocalChecked();
int x = get_integer(obj, prop);