2 #include <node_object_wrap.h>
17 class IndexObject : public node::ObjectWrap {
19 static void Init(v8::Local<v8::Object> exports);
25 explicit IndexObject(struct index* idx);
28 static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
29 static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
30 static v8::Persistent<v8::Function> constructor;
33 v8::Persistent<v8::Function> IndexObject::constructor;
35 IndexObject::IndexObject(struct index* idx0) : idx(idx0), value_(0.) {
38 IndexObject::~IndexObject() {
41 void IndexObject::Init(v8::Local<v8::Object> exports) {
42 v8::Isolate* isolate = exports->GetIsolate();
44 // Prepare constructor template
45 v8::Local<v8::FunctionTemplate> tpl =
46 v8::FunctionTemplate::New(isolate, New);
47 tpl->SetClassName(v8::String::NewFromUtf8(isolate, "Index"));
48 tpl->InstanceTemplate()->SetInternalFieldCount(1);
51 NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
53 constructor.Reset(isolate, tpl->GetFunction());
55 v8::String::NewFromUtf8(isolate, "Index"),
60 void IndexObject::New(const v8::FunctionCallbackInfo<v8::Value>& args) {
61 v8::Isolate* isolate = args.GetIsolate();
63 if (args.IsConstructCall()) {
64 // Invoked as constructor: `new Index(...)`
65 v8::String::Utf8Value* prefix =
66 args[0]->IsUndefined() ? NULL : new v8::String::Utf8Value(args[0]);
67 struct index* idx = NULL;;
68 int lopts = INDEX_LOAD_NOOPT;
69 struct index_load_opt lopt;
71 lopts |= INDEX_LOAD_IGNORE_VERSION; /* quick hack */
75 prefix ? **prefix : "index",
82 isolate->ThrowException(
83 v8::String::NewFromUtf8(isolate, "Unable to load index")
88 IndexObject* obj = new IndexObject(idx);
89 obj->Wrap(args.This());
90 args.GetReturnValue().Set(args.This());
93 // Invoked as plain function `Index(...)`, turn into construct call.
95 v8::Local<v8::Value> argv[argc] = { args[0] };
96 v8::Local<v8::Context> context = isolate->GetCurrentContext();
97 v8::Local<v8::Function> cons =
98 v8::Local<v8::Function>::New(isolate, constructor);
99 v8::Local<v8::Object> result =
100 cons->NewInstance(context, argc, argv).ToLocalChecked();
101 args.GetReturnValue().Set(result);
105 void IndexObject::PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args) {
106 v8::Isolate* isolate = args.GetIsolate();
108 IndexObject* obj = node::ObjectWrap::Unwrap<IndexObject>(args.Holder());
111 args.GetReturnValue().Set(v8::Number::New(isolate, obj->value_));
114 void InitAll(v8::Local<v8::Object> exports) {
115 IndexObject::Init(exports);
118 NODE_MODULE(NODE_GYP_MODULE_NAME, InitAll)