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 NODE_API_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_NODE_API_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 NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, args, &_this, nullptr));
48
49 napi_valuetype valuetype;
50 NODE_API_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 NODE_API_CALL(env, napi_get_value_uint32(env, args[0], &obj->counter_));
58 }
59
60 obj->env_ = env;
61 NODE_API_CALL(env,
62 napi_wrap(
63 env, _this, obj, MyObject::Destructor, nullptr /* finalize_hint */,
64 &obj->wrapper_));
65
66 return _this;
67 }
68
NewInstance(napi_env env,napi_value arg,napi_value * instance)69 napi_status MyObject::NewInstance(napi_env env,
70 napi_value arg,
71 napi_value* instance) {
72 napi_status status;
73
74 const int argc = 1;
75 napi_value argv[argc] = {arg};
76
77 napi_value cons;
78 status = napi_get_reference_value(env, constructor, &cons);
79 if (status != napi_ok) return status;
80
81 status = napi_new_instance(env, cons, argc, argv, instance);
82 if (status != napi_ok) return status;
83
84 return napi_ok;
85 }
86
PlusOne(napi_env env,napi_callback_info info)87 napi_value MyObject::PlusOne(napi_env env, napi_callback_info info) {
88 napi_value _this;
89 NODE_API_CALL(env,
90 napi_get_cb_info(env, info, nullptr, nullptr, &_this, nullptr));
91
92 MyObject* obj;
93 NODE_API_CALL(env, napi_unwrap(env, _this, reinterpret_cast<void**>(&obj)));
94
95 obj->counter_ += 1;
96
97 napi_value num;
98 NODE_API_CALL(env, napi_create_uint32(env, obj->counter_, &num));
99
100 return num;
101 }
102