77 lines
3.1 KiB
JavaScript
77 lines
3.1 KiB
JavaScript
module.exports = function (RED) {
|
|
"use strict";
|
|
|
|
function WooCommerceCustomerNode(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 || "search";
|
|
|
|
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 "search": {
|
|
const params = new URLSearchParams();
|
|
if (msg.email) params.append("email", msg.email);
|
|
if (msg.limit) params.append("per_page", msg.limit);
|
|
if (msg.page) params.append("page", msg.page);
|
|
const qs = params.toString();
|
|
doRequest("GET", "/customers" + (qs ? "?" + qs : ""), undefined, msg, done);
|
|
break;
|
|
}
|
|
case "get": {
|
|
const id = msg.customerId || msg.payload;
|
|
if (!id) { node.error("Missing customerId"); if (done) done(new Error("Missing customerId")); return; }
|
|
doRequest("GET", "/customers/" + encodeURIComponent(id), undefined, msg, done);
|
|
break;
|
|
}
|
|
case "create": {
|
|
const body = msg.payload && typeof msg.payload === "object" ? msg.payload : {
|
|
email: msg.email || "",
|
|
first_name: msg.firstname || msg.firstName || "",
|
|
last_name: msg.lastname || msg.lastName || "",
|
|
username: msg.username || "",
|
|
billing: msg.billing || {},
|
|
shipping: msg.shipping || {}
|
|
};
|
|
doRequest("POST", "/customers", body, msg, done);
|
|
break;
|
|
}
|
|
default: {
|
|
const err = new Error("Unknown operation: " + op);
|
|
node.error(err);
|
|
if (done) done(err);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
RED.nodes.registerType("woocommerce-customer", WooCommerceCustomerNode);
|
|
};
|