neon-bindings / neon

Rust bindings for writing safe and fast native Node.js modules.
https://www.neon-bindings.com/
Apache License 2.0
8k stars 283 forks source link

Return jsobject or undefined #965

Closed stevenliebregt closed 1 year ago

stevenliebregt commented 1 year ago

Hi, I'm trying to create a function, that based on some parameter returns either a JSObject or undefined/null.

The returntype I have is JsResult<JsObject> because I can't find a way to do it optional.

Is this supported?

kjvalencik commented 1 year ago

Yes, it is! This is documented in the type hierarchy. The JsValue type is a super type of all types. You can upcast() to a JsValue from any type to unify two different types.

fn object_or_undefined(mut cx: FunctionContext) -> JsResult<JsValue> {
    let create_object = cx.argument::<JsBoolean>(0)?.value(&mut cx);

    if create_object {
        return Ok(cx.empty_object().upcast());
    }

    Ok(cx.undefined().upcast())
}
stevenliebregt commented 1 year ago

Ah that makes sense, must've missed that, thanks a lot!