I want to access the global context from a custom node I'm creating. I want to do this from the editor code (html file) in the onprepare function. I read in (javascript - Send data on configuration - Stack Overflow) that in order to access the context (runtime) from the editor code (which runs in the browser), I can create a RED api in my js file, and call that api from my editor code.
However I don't know how I can access the context from that API I'm creating. this.context().global is not available there (see below).
module.exports = function (RED) {
function ModelConfigurationNode(config) {
RED.nodes.createNode(this, config);
this.name = config.name;
this.models = config.models;
}
RED.nodes.registerType("model-configuration", ModelConfigurationNode);
// api to be able to communicate between editor and runtime to read the global context
RED.httpAdmin.post(
"/custompath/models",
RED.auth.needsPermission("model-configuration.read"),
function (req, res) {
// read body of the request
var body = req.body;
// ACCESS CONTEXT ????
}
);
};
Thank you for your answer.
Can you provide some more information?
My requirement is to write some data to the global context whenever a user saves some properties in the edit dialog of my custom node.
How can I read the context from the editor? Can I also write to it?
I tried your code but it never finds the node even though the id is correctly sent from the editor:
function (req, res) {
// read body of the request
var body = req.body;
const id = req.params.id;
const node = RED.nodes.getNode(id);
if (node) {
res.sendStatus(200);
}
else {
res.sendStatus(404); // always get a 404, since node is not found
}
}
I also tried getting the context through below code, but this also does not work.
RED.nodes.getContext('global') // TypeError: RED.nodes.getContext is not a function
Well... since you are only looking for the global context you can simplify it like this:
let globalContext;
RED.httpAdmin.post(
"/custompath/models",
RED.auth.needsPermission("model-configuration.read"),
function (req, res) {
const body = req.body;
if (!globalContext) {
RED.nodes.eachNode((node) =>
globalContext = node.context().global;
return false; // Not sure but should breaks the loop
);
} else {
// Write your code here
}
}
);