@hypericon/node-red-hypertable
Version:
Node-RED plugin to interact with Hypertable
101 lines (71 loc) • 3.19 kB
JavaScript
const axios = require("axios").default;
// https://nodered.org/docs/creating-nodes/node-js
const nodeInit = (RED) => {
function readCollectionNode(config) {
RED.nodes.createNode(this, config);
// Retrieve the connection config node
this.connection = RED.nodes.getNode(config.connection);
// this.log("Connection: " + JSON.stringify(this.connection, null, 2));
// Called whenever a message arrives at the node
this.on('input', async (msg, send, done) => {
/** @type string */
const collectionId = msg.collectionId || config.collectionId;
if (!collectionId) return done(new Error("No collection ID is specified"));
// Ensure the connection is defined
if (!this.connection) return done(new Error("No Hypertable connection is defined"));
/** @type string */
let baseUrl = this.connection.baseUrl;
if (!baseUrl) return done(new Error("No base URL is specified in the connection"));
baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/";
/** @type string */
const projectId = this.connection.projectId;
if (!baseUrl) return done(new Error("No project ID is specified in the connection"));
/** @type string */
const apiKey = this.connection.apiKey;
if (!apiKey) return done(new Error("No API key is specified in the connection"));
const path = `${baseUrl}api/v1/data/projects/${projectId}/collections/${collectionId}`;
try {
// this.log(`GET ${path}`);
const response = await axios.get(path, {
responseType: "json",
headers: {
"Authorization": `Basic ${apiKey}`,
},
});
// this.log(`Collection data: ${JSON.stringify(response.data, null, 2)}`);
msg.collection = response.data;
} catch (error) {
this.error(error);
return done(new Error(`Error making HTTP request: ${error}`));
}
// Sends the message to following Nodes
this.send(msg);
// Multiple outputs
// this.send([ msg1 , msg2 ]);
// Multiple messages
// this.send([ [msgA1 , msgA2 , msgA3] , msg2 ]);
// // Handle errors
// const err = new Error();
// if (err) {
// done(err);
// }
// this.log("Something happened");
// this.warn("Something happened you should know about");
// this.error("Oh no, something bad happened");
// // Since Node-RED 0.17
// this.trace("Log some internal detail not needed for normal operation");
// this.debug("Log something more details for debugging the node's behaviour");
// Status API docs: https://nodered.org/docs/creating-nodes/status
// this.status({fill:"red",shape:"ring",text:"disconnected"});
});
// Tidy up state on redeploying flows
this.on('close', function(done) {
// tidy up any state
// Call done() after async work
done();
});
}
// Register the configured Node wih Node-RED
RED.nodes.registerType("read-collection", readCollectionNode);
}
module.exports = nodeInit;