Zammad API nodes for Node-RED
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
module.exports = function (RED) {
|
||||
"use strict";
|
||||
|
||||
const https = require("https");
|
||||
const http = require("http");
|
||||
|
||||
function ZammadConfigNode(config) {
|
||||
RED.nodes.createNode(this, config);
|
||||
const node = this;
|
||||
|
||||
node.baseUrl = (config.baseUrl || "https://support.hanssonit.se/api/v1").replace(/\/+$/, "");
|
||||
node.useToken = config.useToken !== false;
|
||||
node.token = config.token || "";
|
||||
node.username = config.username || "";
|
||||
node.password = config.password || "";
|
||||
|
||||
node.sendRequest = function (method, path, body, msgHeaders, callback) {
|
||||
const url = new URL(node.baseUrl + path);
|
||||
const parsedBody = body !== undefined ? (typeof body === "string" ? body : JSON.stringify(body)) : undefined;
|
||||
|
||||
const headers = Object.assign({ "Accept": "application/json", "Content-Type": "application/json" }, msgHeaders || {});
|
||||
if (parsedBody !== undefined) headers["Content-Length"] = Buffer.byteLength(parsedBody);
|
||||
|
||||
if (node.useToken && node.token) {
|
||||
headers["Authorization"] = "Token token=" + node.token;
|
||||
} else if (node.username && node.password) {
|
||||
headers["Authorization"] = "Basic " + Buffer.from(node.username + ":" + node.password).toString("base64");
|
||||
}
|
||||
|
||||
const options = {
|
||||
method, hostname: url.hostname,
|
||||
port: url.port || (url.protocol === "https:" ? 443 : 80),
|
||||
path: url.pathname + url.search, headers, rejectUnauthorized: false
|
||||
};
|
||||
|
||||
const req = (url.protocol === "https:" ? https : http).request(options, function (res) {
|
||||
let data = "";
|
||||
res.on("data", chunk => data += chunk);
|
||||
res.on("end", () => {
|
||||
let parsed = null;
|
||||
if (data) { try { parsed = JSON.parse(data); } catch (e) { parsed = data; } }
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
callback(null, { statusCode: res.statusCode, body: parsed, headers: res.headers });
|
||||
} else {
|
||||
const err = new Error("Zammad API returned status " + res.statusCode + ": " + data);
|
||||
err.statusCode = res.statusCode;
|
||||
err.body = parsed;
|
||||
callback(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on("error", callback);
|
||||
if (parsedBody !== undefined) req.write(parsedBody);
|
||||
req.end();
|
||||
};
|
||||
}
|
||||
|
||||
RED.nodes.registerType("zammad-config", ZammadConfigNode);
|
||||
};
|
||||
Reference in New Issue
Block a user