feat(napi): allow return self as this

This commit is contained in:
LongYinan 2021-11-25 22:31:11 +08:00
parent 1fe39ff66d
commit 9a0de8e485
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
4 changed files with 24 additions and 12 deletions

View file

@ -245,6 +245,8 @@ impl NapiFn {
let js_name = &self.js_name;
if let Some(ty) = &self.ret {
let ty_string = ty.into_token_stream().to_string();
let is_return_self = ty_string == "& Self" || ty_string == "&mut Self";
if self.kind == FnKind::Constructor {
if self.is_ret_result {
quote! { cb.construct(#js_name, #ret?) }
@ -263,19 +265,27 @@ impl NapiFn {
<#ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, #ret)
}
} else {
quote! {
match #ret {
Ok(value) => napi::bindgen_prelude::ToNapiValue::to_napi_value(env, value),
Err(err) => {
napi::bindgen_prelude::JsError::from(err).throw_into(env);
Ok(std::ptr::null_mut())
},
if is_return_self {
quote! { #ret.map(|_| cb.this) }
} else {
quote! {
match #ret {
Ok(value) => napi::bindgen_prelude::ToNapiValue::to_napi_value(env, value),
Err(err) => {
napi::bindgen_prelude::JsError::from(err).throw_into(env);
Ok(std::ptr::null_mut())
},
}
}
}
}
} else {
quote! {
<#ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, #ret)
if is_return_self {
quote! { Ok(cb.this) }
} else {
quote! {
<#ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, #ret)
}
}
}
} else {

View file

@ -112,6 +112,8 @@ impl NapiFn {
let (ts_type, _) = ty_to_ts_type(ret, true);
if ts_type == "undefined" {
"void".to_owned()
} else if ts_type == "Self" {
"this".to_owned()
} else {
ts_type
}

View file

@ -12,7 +12,7 @@ pub static ___CALL_FROM_FACTORY: AtomicBool = AtomicBool::new(false);
pub struct CallbackInfo<const N: usize> {
env: sys::napi_env,
this: sys::napi_value,
pub this: sys::napi_value,
pub args: [sys::napi_value; N],
}

View file

@ -123,8 +123,8 @@ impl Array {
T: ToNapiValue,
{
let mut arr = Array::new(env.0, value.len() as u32)?;
value.into_iter().try_for_each(|val| {
arr.insert(val)?;
value.into_iter().enumerate().try_for_each(|(index, val)| {
arr.set(index as u32, val)?;
Ok::<(), Error>(())
})?;
Ok(arr)