1 #include <node_api.h>
2 #include <assert.h>
3 #include "../../js-native-api/common.h"
4
5 #define MAX_ARGUMENTS 10
6 #define RESERVED_ARGS 3
7
MakeCallback(napi_env env,napi_callback_info info)8 static napi_value MakeCallback(napi_env env, napi_callback_info info) {
9 size_t argc = MAX_ARGUMENTS;
10 size_t n;
11 napi_value args[MAX_ARGUMENTS];
12 // NOLINTNEXTLINE (readability/null_usage)
13 NODE_API_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL));
14
15 NODE_API_ASSERT(env, argc > 0, "Wrong number of arguments");
16
17 napi_value resource = args[0];
18 napi_value recv = args[1];
19 napi_value func = args[2];
20
21 napi_value argv[MAX_ARGUMENTS - RESERVED_ARGS];
22 for (n = RESERVED_ARGS; n < argc; n += 1) {
23 argv[n - RESERVED_ARGS] = args[n];
24 }
25
26 napi_valuetype func_type;
27
28 NODE_API_CALL(env, napi_typeof(env, func, &func_type));
29
30 napi_value resource_name;
31 NODE_API_CALL(env, napi_create_string_utf8(
32 env, "test", NAPI_AUTO_LENGTH, &resource_name));
33
34 napi_async_context context;
35 NODE_API_CALL(env, napi_async_init(env, resource, resource_name, &context));
36
37 napi_value result;
38 if (func_type == napi_function) {
39 NODE_API_CALL(env, napi_make_callback(
40 env, context, recv, func, argc - RESERVED_ARGS, argv, &result));
41 } else {
42 NODE_API_ASSERT(env, false, "Unexpected argument type");
43 }
44
45 NODE_API_CALL(env, napi_async_destroy(env, context));
46
47 return result;
48 }
49
50 static
Init(napi_env env,napi_value exports)51 napi_value Init(napi_env env, napi_value exports) {
52 napi_value fn;
53 NODE_API_CALL(env, napi_create_function(
54 // NOLINTNEXTLINE (readability/null_usage)
55 env, NULL, NAPI_AUTO_LENGTH, MakeCallback, NULL, &fn));
56 NODE_API_CALL(env, napi_set_named_property(env, exports, "makeCallback", fn));
57 return exports;
58 }
59
60 NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
61