Files

66 lines
2.9 KiB
JavaScript
Raw Permalink Normal View History

2026-10-14 23:17:40 +02:00
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://example.com/api/v1").replace(/\/+$/, "");
2026-10-14 23:17:40 +02:00
node.useToken = config.useToken !== false;
node.token = (this.credentials && this.credentials.token) || config.token || "";
node.username = (this.credentials && this.credentials.username) || config.username || "";
node.password = (this.credentials && this.credentials.password) || config.password || "";
2026-10-14 23:17:40 +02:00
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, {
credentials: {
token: { type: "text" },
username: { type: "text" },
password: { type: "password" }
}
});
2026-10-14 23:17:40 +02:00
};