node-red / cookbook.nodered.org

Node-RED Cookbook
http://cookbook.nodered.org
Apache License 2.0
84 stars 34 forks source link

Accessing global context from httpAdmin? #39

Open macinspak opened 5 years ago

macinspak commented 5 years ago

I am writing a custom node, and the intention is that on a successful connection, a token is generated along with some additional attributes that I would like to persist on the node config.

Standard approach has the config node attributes and credentials directly store the returned data. However, this may change over time based on periodic checks, and it should reflect that new state on the config node without having to redeploy.

So the approach I believe may work is to use the http communication with the httpAdmin nodes to set and get the state. I can then query that state on the http oneditprepare and set it on successful config.

I was looking to then use the global context within the httpAdmin endpoints:

RED.httpAdmin.get("/allow2/paired/:id", RED.auth.needsPermission('Allow2Pairing.read'), function(req, res) {
    const nodeId = req.params.id.replace(/\./g, '_');
    const pairing = JSON.parse(RED.globalContext.get('allow2_pairing_' + nodeId) || "{ paired: false }");
    res.json(pairing);
});

RED.httpAdmin.post("/allow2/paired", RED.auth.needsPermission('Allow2Pairing.write'), function(req, res) {
    const nodeId = req.body.id.replace(/\./g, '_');
    RED.globalContext.set('allow2_pairing_' + nodeId, JSON.stringify({
        paired: true,
        children: req.body.children
    }));
    res.json({ status: 'success' });
});

This means that should the token no longer be valid, I can detect that on opening the config node and present the correct interface to gain a new token (shouldn't happen very often). And I can use the config id to retrieve the "children" information at any time to correctly show dropdown values in other nodes.

The complexity is, I believe, that I can't get to the global context from 'RED', only from a node itself, but as none may be deployed in a vanilla installation, then I cannot get to the global context. Is there a way to get a handle to the global context from "RED"?

Alternately, I can also potentially cache the value in memory and then perform the write to global context on deployment, that is a bit of a kludge though.

Alternately, I could also do my own direct file persistence using OS functions from within httpAdmin endpoints.

Any suggestions on a better "preferred" approach?

knolleary commented 5 years ago

Hi, this is the issue tracker for the content on the cookbook site. It isn't the best place to get support on writing your own nodes.

If you check out our contribution guidelines you'll see we prefer to handle this sort of thing on the forum or slack team. If its a general how-to type question, you could ask a question on Stack Overflow and tag it node-red.

Thanks!

Allow2CEO commented 5 years ago

Thanks