Send data on configuration

2019-04-15 03:58发布

问题:

I want to send asynchronous data to the node on configuration. I want to perform a SQL request to list some data in a .

  • On node creation, a server side function is performed
  • When it's done, a callback send data to the node configuration
  • On node configuration, when data is received, the list is created

Alternatively, the binary can request database each x minutes and create a cache that each node will use on creation, this will remove the asynchronous part of code, even if it's no longer "live updated".

In fact, i'm stuck because i created the query and added it as below :

module.exports = function(RED) {
    "use strict";
    var db = require("../bin/database")(RED);

    function testNode(n) {
        // Create a RED node
        RED.nodes.createNode(this,n);

        // Store local copies of the node configuration (as defined in the 
.html
        var node = this;
        var context = this.context();


        this.on('input', function (msg) {
            node.send({payload: true});
        });
    }

    RED.nodes.registerType("SQLTEST",testNode);
}

But I don't know how to pass data to the configuration node. I thought of Socket.IO to do it, but, is this a good idea and is it available? Do you know any solution ?

回答1:

The standard model used in Node-RED is for the node to register its own admin http endpoint that can be used to query the information it needs. You can see this in action with the Serial node.

The Serial node edit dialog lists the currently connected serial devices for you to pick from.

The node registers the admin endpoint here: https://github.com/node-red/node-red-nodes/blob/83ea35d0ddd70803d97ccf488d675d6837beeceb/io/serialport/25-serial.js#L283

RED.httpAdmin.get("/serialports", RED.auth.needsPermission('serial.read'), function(req,res) {
    serialp.list(function (err, ports) {
        res.json(ports);
    });
});

Key points:

  • pick a url that is namespaced to your node type - this avoids clashes
  • the needsPermission middleware is there to ensure only authenticated users can access the endpoint. The permission should be of the form <node-type>.read.

Its edit dialog then queries that endpoint from here: https://github.com/node-red/node-red-nodes/blob/83ea35d0ddd70803d97ccf488d675d6837beeceb/io/serialport/25-serial.html#L240

$.getJSON('serialports',function(data) {
    //... does stuff with data
});

Key points:

  • here the url must not begin with a /. That ensures the request is made relative to wherever the editor is being served from - you cannot assume it is being served from /.