@hypericon/node-red-hypertable
Version:
Node-RED plugin to interact with Hypertable
82 lines (64 loc) • 2.59 kB
JavaScript
const { readConnection } = require("./common");
const axios = require("axios").default;
// https://nodered.org/docs/creating-nodes/node-js
const nodeInit = (RED) => {
function createRecordNode(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"));
// string | object -> convert to object
let recordValues = msg.recordValues || config.recordValues || "{}";
try {
if (typeof recordValues === "string") {
recordValues = JSON.parse(recordValues);
}
} catch (error) {
recordValues = {};
}
// this.log(`Initial record values type: ${typeof recordValues}`);
// this.log(`Initial record values: ${JSON.stringify(recordValues)}`);
let baseUrl, projectId, apiKey;
try {
const conn = readConnection(this.connection);
baseUrl = conn.baseUrl;
// workspaceId = conn.workspaceId;
projectId = conn.projectId;
apiKey = conn.apiKey;
} catch (error) {
return done(error);
}
const path = `${baseUrl}api/v1/data/projects/${projectId}/collections/${collectionId}/records`;
try {
// this.log(`POST ${path}`);
// this.log(`body: ${JSON.stringify({ values: recordValues })}`);
// this.log(`API key: ${apiKey}`);
const response = await axios.post(path, {
values: recordValues,
}, {
responseType: "json",
headers: {
"Authorization": `Basic ${apiKey}`,
"Content-Type": "application/json",
"Accept": "*/*",
},
});
// this.log(`Response data: ${JSON.stringify(response.data, null, 2)}`);
msg.record = response.data.record;
} catch (error) {
this.error(error);
return done(new Error(`Error making HTTP request: ${error}`));
}
// Sends the message to following Nodes
this.send(msg);
});
}
// Register the configured Node wih Node-RED
RED.nodes.registerType("create-record", createRecordNode);
}
module.exports = nodeInit;