1 #include "myobject.h"
2 #include "../common.h"
3
4 static int finalize_count = 0;
5
MyObject()6 MyObject::MyObject() : env_(nullptr), wrapper_(nullptr) {}
7
~MyObject()8 MyObject::~MyObject() { napi_delete_reference(env_, wrapper_); }
9
Destructor(napi_env env,void * nativeObject,void *)10 void MyObject::Destructor(napi_env env,
11 void* nativeObject,
12 void* /*finalize_hint*/) {
13 ++finalize_count;
14 MyObject* obj = static_cast<MyObject*>(nativeObject);
15 delete obj;
16 }
17
GetFinalizeCount(napi_env env,napi_callback_info info)18 napi_value MyObject::GetFinalizeCount(napi_env env, napi_callback_info info) {
19 napi_value result;
20 NAPI_CALL(env, napi_create_int32(env, finalize_count, &result));
21 return result;
22 }
23
24 napi_ref MyObject::constructor;
25
Init(napi_env env)26 napi_status MyObject::Init(napi_env env) {
27 napi_status status;
28 napi_property_descriptor properties[] = {
29 DECLARE_NAPI_PROPERTY("plusOne", PlusOne),
30 };
31
32 napi_value cons;
33 status = napi_define_class(
34 env, "MyObject", -1, New, nullptr, 1, properties, &cons);
35 if (status != napi_ok) return status;
36
37 status = napi_create_reference(env, cons, 1, &constructor);
38 if (status != napi_ok) return status;
39
40 return napi_ok;
41 }
42
New(napi_env env,napi_callback_info info)43 napi_value MyObject::New(napi_env env, napi_callback_info info) {
44 size_t argc = 1;
45 napi_value args[1];
46 napi_value _this;
47 NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr));
48
49 napi_valuetype valuetype;
50 NAPI_CALL(env, napi_typeof(env, args[0], &valuetype));
51
52 MyObject* obj = new MyObject();
53
54 if (valuetype == napi_undefined) {
55 obj->counter_ = 0;
56 } else {
57 NAPI_CALL(env, napi_get_value_uint32(env, args[0], &obj->counter_));
58 }
59
60 obj->env_ = env;
61 NAPI_CALL(env, napi_wrap(env,
62 _this,
63 obj,
64 MyObject::Destructor,
65 nullptr, /* finalize_hint */
66 &obj->wrapper_));
67
68 return _this;
69 }
70
NewInstance(napi_env env,napi_value arg,napi_value * instance)71 napi_status MyObject::NewInstance(napi_env env,
72 napi_value arg,
73 napi_value* instance) {
74 napi_status status;
75
76 const int argc = 1;
77 napi_value argv[argc] = {arg};
78
79 napi_value cons;
80 status = napi_get_reference_value(env, constructor, &cons);
81 if (status != napi_ok) return status;
82
83 status = napi_new_instance(env, cons, argc, argv, instance);
84 if (status != napi_ok) return status;
85
86 return napi_ok;
87 }
88
PlusOne(napi_env env,napi_callback_info info)89 napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) {
90 napi_value _this;
91 NAPI_CALL(env,
92 napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr));
93
94 MyObject* obj;
95 NAPI_CALL(env, napi_unwrap(env, _this, reinterpret_cast<void**>(&obj)));
96
97 obj->counter_ += 1;
98
99 napi_value num;
100 NAPI_CALL(env, napi_create_uint32(env, obj->counter_, &num));
101
102 return num;
103 }
104