From ff717df34f9df1494c312c999c3d16d17d6c748f Mon Sep 17 00:00:00 2001 From: LongYinan Date: Tue, 7 Dec 2021 21:49:45 +0800 Subject: [PATCH] fix(napi-derive-backend): skip set object property if it is None --- crates/backend/src/codegen/struct.rs | 20 ++++++++++++++++++-- examples/napi/__test__/values.spec.ts | 2 +- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/backend/src/codegen/struct.rs b/crates/backend/src/codegen/struct.rs index e09af144..d9aa1c75 100644 --- a/crates/backend/src/codegen/struct.rs +++ b/crates/backend/src/codegen/struct.rs @@ -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 { diff --git a/examples/napi/__test__/values.spec.ts b/examples/napi/__test__/values.spec.ts index a66153cb..e2a30783 100644 --- a/examples/napi/__test__/values.spec.ts +++ b/examples/napi/__test__/values.spec.ts @@ -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')