OpenHausIO / backend

HTTP API for the OpenHaus SmartHome/IoT solution
https://docs.open-haus.io
6 stars 2 forks source link

Create a `injectMethod()` method #463

Closed mStirner closed 6 months ago

mStirner commented 6 months ago

Due to #460 a .bridge method cant be directly added to class.interface.js. Doing so, would create a circular reference because the device item (or at leas the _id property) needs to be passed into the interface instances. (The _id i used to tell the connector on which device + interface a connection needs to be established).

It would be better to inject/add the .bridge method for the interface instance in the file class.devcie.js: https://github.com/OpenHausIO/backend/blob/b8f52009c0cf919ffe374b9b733e97d762b8224b/components/devices/class.device.js#L50

For that a injectMethod needs to be created, that add a property to the prototype of the given object. (Which is absolutely the same as if the method was defined in the class body).

function injectMethod(obj, prop, value, options = {}){
    Object.defineProperty(Object.getPrototypeOf(obj), prop, {
        value,
        writable: true,
        enumerable: false,
        configurable: true,
        ...options
    });
}

This method could also be used in the system/component method definition: https://github.com/OpenHausIO/backend/blob/b8f52009c0cf919ffe374b9b733e97d762b8224b/system/component/class.common.js#L38-L41

Instead of add a method to this, wrap it in the injectMethod method:

_defineMethod(name, executor) {
    injectMethod(this, name, (...args) => {
        ...
    });
});
mStirner commented 6 months ago

A test breaks when used for injecting the .bridge method into a interface instance. Wihtout Object.getPrototype... it works. Otherwise only the last interface this method is used, create bridge requests.