Skip to content

Commit

Permalink
fix(napi): missing coerce_to_bool on JsValue
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed Nov 21, 2021
1 parent 5c3bccf commit 4aa56a1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
13 changes: 12 additions & 1 deletion crates/napi/src/js_values/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,18 @@ macro_rules! impl_js_value_methods {
unsafe { JsUnknown::from_raw_unchecked(self.0.env, self.0.value) }
}

pub fn coerce_to_bool(self) -> Result<JsBoolean> {
let mut new_raw_value = ptr::null_mut();
check_status!(unsafe {
sys::napi_coerce_to_bool(self.0.env, self.0.value, &mut new_raw_value)
})?;
Ok(JsBoolean(Value {
env: self.0.env,
value: new_raw_value,
value_type: ValueType::Boolean,
}))
}

pub fn coerce_to_number(self) -> Result<JsNumber> {
let mut new_raw_value = ptr::null_mut();
check_status!(unsafe {
Expand Down Expand Up @@ -190,7 +202,6 @@ macro_rules! impl_js_value_methods {
}

#[cfg(feature = "napi5")]

pub fn is_date(&self) -> Result<bool> {
let mut is_date = true;
check_status!(unsafe { sys::napi_is_date(self.0.env, self.0.value, &mut is_date) })?;
Expand Down
11 changes: 11 additions & 0 deletions examples/napi-compat-mode/__test__/env.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,14 @@ test('should be able to throw syntax error', (t) => {
t.is((e as SyntaxError).message, msg)
}
})

test('should be able to coerceToBool', (t) => {
t.true(bindings.coerceToBool(true))
t.true(bindings.coerceToBool(1))
t.true(bindings.coerceToBool({}))
t.true(bindings.coerceToBool(Symbol()))
t.false(bindings.coerceToBool(0))
t.false(bindings.coerceToBool(undefined))
t.false(bindings.coerceToBool(null))
t.false(bindings.coerceToBool(NaN))
})
7 changes: 7 additions & 0 deletions examples/napi-compat-mode/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ pub fn throw_syntax_error(ctx: CallContext) -> Result<JsUndefined> {
ctx.env.get_undefined()
}

#[js_function(1)]
fn coerce_to_bool(ctx: CallContext) -> Result<JsBoolean> {
let arg: JsUnknown = ctx.get(0)?;
arg.coerce_to_bool()
}

pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("instanceof", instanceof)?;
exports.create_named_method("isTypedarray", is_typedarray)?;
Expand All @@ -61,5 +67,6 @@ pub fn register_js(exports: &mut JsObject) -> Result<()> {
exports.create_named_method("castUnknown", cast_unknown)?;
exports.create_named_method("getEnvVariable", get_env_variable)?;
exports.create_named_method("throwSyntaxError", throw_syntax_error)?;
exports.create_named_method("coerceToBool", coerce_to_bool)?;
Ok(())
}

0 comments on commit 4aa56a1

Please sign in to comment.