diff --git a/test_module/__test__/class.spec.ts b/test_module/__test__/class.spec.ts index 1d7acf07..d681097d 100644 --- a/test_module/__test__/class.spec.ts +++ b/test_module/__test__/class.spec.ts @@ -11,3 +11,11 @@ test('should create class', (t) => { testClass.addCount(add) t.is(testClass.count, fixture + add) }) + +test('should be able to manipulate wrapped native value', (t) => { + const TestClass = bindings.createTestClass() + const fixture = 20 + const testClass = new TestClass(fixture) + const add = 101 + t.is(testClass.addNativeCount(add), fixture + add + 100) +}) diff --git a/test_module/src/class.rs b/test_module/src/class.rs index 8d5fa5ef..d62c27b5 100644 --- a/test_module/src/class.rs +++ b/test_module/src/class.rs @@ -2,10 +2,15 @@ use std::convert::TryInto; use napi::{CallContext, JsFunction, JsNumber, JsObject, JsUndefined, Module, Property, Result}; +struct NativeClass { + value: i32, +} + #[js_function(1)] fn create_test_class(ctx: CallContext) -> Result { let add_count_method = Property::new(&ctx.env, "addCount")?.with_method(add_count); - let properties = vec![add_count_method]; + let add_native_count = Property::new(&ctx.env, "addNativeCount")?.with_method(add_native_count); + let properties = vec![add_count_method, add_native_count]; ctx .env .define_class("TestClass", test_class_constructor, properties.as_slice()) @@ -13,9 +18,12 @@ fn create_test_class(ctx: CallContext) -> Result { #[js_function(1)] fn test_class_constructor(ctx: CallContext) -> Result { - let count = ctx.get::(0)?; + let count: i32 = ctx.get::(0)?.try_into()?; let mut this: JsObject = ctx.this_unchecked(); - this.set_named_property("count", ctx.env.create_int32(count.try_into()?)?)?; + ctx + .env + .wrap(&mut this, NativeClass { value: count + 100 })?; + this.set_named_property("count", ctx.env.create_int32(count)?)?; ctx.env.get_undefined() } @@ -28,6 +36,15 @@ fn add_count(ctx: CallContext) -> Result { ctx.env.get_undefined() } +#[js_function(1)] +fn add_native_count(ctx: CallContext) -> Result { + let add: i32 = ctx.get::(0)?.try_into()?; + let this: JsObject = ctx.this_unchecked(); + let native_class: &mut NativeClass = ctx.env.unwrap(&this)?; + native_class.value = native_class.value + add; + ctx.env.create_int32(native_class.value) +} + pub fn register_js(module: &mut Module) -> Result<()> { module.create_named_method("createTestClass", create_test_class)?; Ok(())