module.exports = function (RED) { "use strict"; function WooCommerceProductNode(config) { RED.nodes.createNode(this, config); const node = this; node.configNode = RED.nodes.getNode(config.config); if (!node.configNode) { node.error("No woocommerce-config node configured"); return; } node.operation = config.operation || "list"; node.status({ fill: "blue", shape: "ring", text: "ready" }); function doRequest(method, path, body, msg, done) { node.status({ fill: "yellow", shape: "dot", text: method + " " + path }); node.configNode.sendRequest(method, path, body, {}, function (err, result) { if (err) { node.status({ fill: "red", shape: "ring", text: "error" }); if (done) done(err); else node.error(err, msg); return; } msg.payload = result.body; msg.statusCode = result.statusCode; msg.woocommerce = result; node.status({ fill: "green", shape: "dot", text: result.statusCode }); done(); }); } node.on("input", function (msg, send, done) { const op = msg.operation || node.operation; switch (op) { case "list": { const params = new URLSearchParams(); if (msg.limit) params.append("per_page", msg.limit); if (msg.page) params.append("page", msg.page); if (msg.category) params.append("category", msg.category); if (msg.search) params.append("search", msg.search); const qs = params.toString(); doRequest("GET", "/products" + (qs ? "?" + qs : ""), undefined, msg, done); break; } case "get": { const id = msg.productId || msg.payload; if (!id) { node.error("Missing productId"); if (done) done(new Error("Missing productId")); return; } doRequest("GET", "/products/" + encodeURIComponent(id), undefined, msg, done); break; } default: { const err = new Error("Unknown operation: " + op); node.error(err); if (done) done(err); } } }); } RED.nodes.registerType("woocommerce-product", WooCommerceProductNode); };