-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnode.js
95 lines (82 loc) · 2.83 KB
/
node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"use strict";
const lib = require("./lib.js");
module.exports = function (RED) {
class OpenaiApiNode {
constructor(config) {
RED.nodes.createNode(this, config);
let node = this;
node.service = RED.nodes.getNode(config.service);
node.config = config;
node.on("input", function (msg) {
let clientApiKey = node.service.credentials.secureApiKeyValue || "";
let clientApiBase = node.service.apiBase;
let clientOrganization = node.service.organizationId;
let client = new lib.OpenaiApi(
clientApiKey,
clientApiBase,
clientOrganization
);
let payload;
const propertyType = node.config.propertyType || "msg";
const propertyPath = node.config.property || "payload";
if (propertyType === "msg") {
payload = RED.util.getMessageProperty(msg, propertyPath);
} else {
// For flow and global contexts
payload = node.context()[propertyType].get(propertyPath);
}
const serviceName = node.config.method; // Set the service name to call.
let serviceParametersObject = {
_node: node,
payload: payload,
msg: msg,
};
// Dynamically call the function based on the service name
if (typeof client[serviceName] === "function") {
node.status({
fill: "blue",
shape: "dot",
text: "OpenaiApi.status.requesting",
});
client[serviceName](serviceParametersObject)
.then((payload) => {
if (payload !== undefined) {
// Update `msg.payload` with the payload from the API response, then send resonse to client.
msg.payload = payload;
node.send(msg);
node.status({});
}
})
.catch(function (error) {
node.status({
fill: "red",
shape: "ring",
text: "node-red:common.status.error",
});
let errorMessage = error.message;
node.error(errorMessage, msg);
});
} else {
console.error(`Function ${serviceName} does not exist on client.`);
}
});
}
}
RED.nodes.registerType("OpenAI API", OpenaiApiNode);
class ServiceHostNode {
constructor(n) {
RED.nodes.createNode(this, n);
this.secureApiKeyValue = n.secureApiKeyValue;
this.apiBase = n.apiBase;
this.secureApiKeyHeaderOrQueryName = n.secureApiKeyHeaderOrQueryName;
this.secureApiKeyIsQuery = n.secureApiKeyIsQuery;
this.organizationId = n.organizationId;
}
}
RED.nodes.registerType("Service Host", ServiceHostNode, {
credentials: {
secureApiKeyValue: { type: "password" },
temp: { type: "text" },
},
});
};