fix(napi-derive-backend): skip set object property if it is None

This commit is contained in:
LongYinan 2021-12-07 21:49:45 +08:00
parent f7a101db01
commit ff717df34f
No known key found for this signature in database
GPG key ID: C3666B7FC82ADAD7
2 changed files with 19 additions and 3 deletions

View file

@ -255,7 +255,15 @@ impl NapiStruct {
match &field.name {
syn::Member::Named(ident) => {
field_destructions.push(quote! { #ident });
obj_field_setters.push(quote! { obj.set(#field_js_name, #ident)?; });
if is_optional_field {
obj_field_setters.push(quote! {
if #ident.is_some() {
obj.set(#field_js_name, #ident)?;
}
});
} else {
obj_field_setters.push(quote! { obj.set(#field_js_name, #ident)?; });
}
if is_optional_field {
obj_field_getters.push(quote! { let #ident: #ty = obj.get(#field_js_name)?; });
} else {
@ -264,7 +272,15 @@ impl NapiStruct {
}
syn::Member::Unnamed(i) => {
field_destructions.push(quote! { arg#i });
obj_field_setters.push(quote! { obj.set(#field_js_name, arg#1)?; });
if is_optional_field {
obj_field_setters.push(quote! {
if arg#1.is_some() {
obj.set(#field_js_name, arg#i)?;
}
});
} else {
obj_field_setters.push(quote! { obj.set(#field_js_name, arg#1)?; });
}
if is_optional_field {
obj_field_getters.push(quote! { let arg#i: #ty = obj.get(#field_js_name)?; });
} else {

View file

@ -224,7 +224,7 @@ test('serde-json', (t) => {
const packageJson = readPackageJson()
t.is(packageJson.name, 'napi-rs')
t.is(packageJson.version, '0.0.0')
t.is(packageJson.dependencies, null)
t.is(packageJson.dependencies, undefined)
t.snapshot(Object.keys(packageJson.devDependencies!).sort())
t.is(getPackageJsonName(packageJson), 'napi-rs')