Files
nextcloud-nodered-woocommerce/nodes/woocommerce-config.js
T

66 lines
2.9 KiB
JavaScript
Raw Normal View History

2026-10-14 23:18:22 +02:00
module.exports = function (RED) {
"use strict";
const https = require("https");
const http = require("http");
function WooCommerceConfigNode(config) {
RED.nodes.createNode(this, config);
const node = this;
node.baseUrl = (config.baseUrl || "https://example.com/wp-json/wc/v3").replace(/\/+$/, "");
// Credentials from node-RED credentials tab OR from config node fields
node.consumerKey = (this.credentials && this.credentials.consumerKey) || config.consumerKey || "";
node.consumerSecret = (this.credentials && this.credentials.consumerSecret) || config.consumerSecret || "";
2026-10-14 23:18:22 +02:00
node.sendRequest = function (method, path, body, msgHeaders, callback) {
const url = new URL(node.baseUrl + path);
// Append consumer_key and consumer_secret as query parameters (proven working in curl)
if (node.consumerKey) {
url.searchParams.set('consumer_key', node.consumerKey);
}
if (node.consumerSecret) {
url.searchParams.set('consumer_secret', node.consumerSecret);
}
2026-10-14 23:18:22 +02:00
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);
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("WooCommerce 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("woocommerce-config", WooCommerceConfigNode, {
credentials: {
consumerKey: { type: "text" },
consumerSecret: { type: "password" }
}
});
};