File: objectwrap_function.cc

package info (click to toggle)
node-addon-api 8.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,248 kB
  • sloc: cpp: 15,431; javascript: 5,631; ansic: 157; makefile: 7
file content (43 lines) | stat: -rw-r--r-- 1,545 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <napi.h>
#include <unordered_map>
#include "test_helper.h"

class FunctionTest : public Napi::ObjectWrap<FunctionTest> {
 public:
  FunctionTest(const Napi::CallbackInfo& info)
      : Napi::ObjectWrap<FunctionTest>(info) {}

  static Napi::Value OnCalledAsFunction(const Napi::CallbackInfo& info) {
    // If called with a "true" argument, throw an exeption to test the handling.
    if (!info[0].IsUndefined() && MaybeUnwrap(info[0].ToBoolean())) {
      NAPI_THROW(Napi::Error::New(info.Env(), "an exception"), Napi::Value());
    }
    // Otherwise, act as a factory.
    std::vector<napi_value> args;
    for (size_t i = 0; i < info.Length(); i++) args.push_back(info[i]);
    return MaybeUnwrap(GetConstructor(info.Env()).New(args));
  }

  static void Initialize(Napi::Env env, Napi::Object exports) {
    const char* name = "FunctionTest";
    Napi::Function func = DefineClass(env, name, {});
    Napi::FunctionReference* ctor = new Napi::FunctionReference();
    *ctor = Napi::Persistent(func);
    env.SetInstanceData(ctor);
    exports.Set(name, func);
  }

  static Napi::Function GetConstructor(Napi::Env env) {
    return env.GetInstanceData<Napi::FunctionReference>()->Value();
  }
};

Napi::Value ObjectWrapFunctionFactory(const Napi::CallbackInfo& info) {
  Napi::Object exports = Napi::Object::New(info.Env());
  FunctionTest::Initialize(info.Env(), exports);
  return exports;
}

Napi::Object InitObjectWrapFunction(Napi::Env env) {
  return Napi::Function::New<ObjectWrapFunctionFactory>(env, "FunctionFactory");
}