I have a function-file node in which I would like to use configs which are stored in the global context.
I am struggling because my approach appears to mutate the global context which I do not want. I am not sure whether I am misunderstanding Node-red, JavaScript or what?
The basic principle is that there is a bunch of config in the global context for sensors and devices. Sensors reference the device upon which they are mounted. Devices reference the room in which they are located.
global.const = {
sensors: [
{
name: 'sensor_light_1',
device: 'room_1',
},
{
name: 'sensor_humidity',
device: 'room_1',
},
{
name: 'sensor_temp',
device: 'room_2',
}
],
devices: [
{
name: 'room_1',
location: 'bedroom',
},
{
name: 'room_2',
location: 'kitchen',
}
]
}
I would like to be able to create a means of retrieving a sensor config and replacing the reference to the device with the device's config:
// Transforming this
{
name: 'sensor_light_1',
device: 'room_1',
}
// Into this
{
name: 'sensor_light_1',
device: {
name: 'room_1',
location: 'bedroom',
}
}
However, my approach seems to modify the Global context replacing the sensor config with the combined result.
A simplified example is here:
class Sensors {
constructor(config) {
this.sensors = config.sensors;
this.devices = config.devices;
}
getSensor(sensorName) {
// Find the sensor config with the matching name
const sensor = this.sensors
.find((sensor) => sensor.name === sensorName);
// Pass the config to a method with replaces the
// device name property with that device's config
return this.addDevice(sensor);
}
addDevice(sensor) {
const sensorWithDevice = sensor;
// Find the device config with the matching name
const sensorDevice = this.devices
.find((device) => device.name === sensor.device);
// Replace the name property in the sensor config
// with the device config
sensorWithDevice.device = sensorDevice;
return sensorWithDevice;
}
}
const sensors = new Sensors({
sensors: global.get('const').sensors,
devices: global.get('const').devices,
});
msg.payload = sensors.getSensor('sensor_light_1');
return msg;