node-addon-api icon indicating copy to clipboard operation
node-addon-api copied to clipboard

Discussion: How to avoid manually setting descriptors for each attribute?

Open edoCsItahW opened this issue 6 months ago • 3 comments

How to avoid manually setting descriptors for each attribute

There is a class that has many properties, but I have a way to dynamically collect these properties, so I use Maps to store them and hope they can be exposed to Nodejs. That's where the problem lies.


Assuming that according to the process, it should be like this

class A {
    private:
        attr1;
        attr2;
        ...
    
    public:
        getAttr1();
        setAttr1(attr);
        getAttr2();
        setAttr2();
        
        Init(env, exports) {
            func = DefineClass(env, "A", {
                InstanceAccessor("attr1", &A::getAttr1, &A::setAttr1),
                InstanceAccessor("attr1", &A::getAttr2, &A::setAttr2),
                ...
            })
        }
}

But I don't want to set descriptors for every attribute, so I made the following attempts

  1. Use decorators
// Definition in napi. h
using InstanceGetterCallback = Napi::Value (T::*)(const CallbackInfo& info);
using InstanceSetterCallback = void (T::*)(const CallbackInfo& info, const Napi::Value& value);

This doesn't work because the T::* in InstanceGetterCallback restricts my return type from being a free function

  1. Retrieve the key from the parameters received by the Setter function
set(const Napi::CallbackInfo& info, const Napi::Value& value)

But info does not contain a key, it contains the same value as value, and the key passed in by the user is unknown what has taken it away

So do you have any good methods?

edoCsItahW avatar Aug 05 '24 13:08 edoCsItahW