forked from rgstephens/node-red-contrib-graphql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphql.js
444 lines (420 loc) · 16.5 KB
/
graphql.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
module.exports = function(RED) {
// https://github.com/axios/axios
var axios = require("axios");
var mustache = require("mustache");
var vers = "0.2.3";
function safeJSONStringify(input, maxDepth) {
var output,
refs = [],
refsPaths = [];
maxDepth = maxDepth || 5;
function recursion(input, path, depth) {
var output = {},
pPath,
refIdx;
path = path || "";
depth = depth || 0;
depth++;
if (maxDepth && depth > maxDepth) {
return "{depth over " + maxDepth + "}";
}
for (var p in input) {
pPath = (path ? path + "." : "") + p;
if (typeof input[p] === "function") {
output[p] = "{function}";
} else if (typeof input[p] === "object") {
refIdx = refs.indexOf(input[p]);
if (-1 !== refIdx) {
output[p] = "{reference to " + refsPaths[refIdx] + "}";
} else {
refs.push(input[p]);
refsPaths.push(pPath);
output[p] = recursion(input[p], pPath, depth);
}
} else {
output[p] = input[p];
}
}
return output;
}
if (typeof input === "object") {
output = recursion(input);
} else {
output = input;
}
return JSON.stringify(output);
}
function GraphqlNode(config) {
RED.nodes.createNode(this, config);
var node = this;
//node.status({ fill:"blue", shape:"ring", text:"connecting" });
RED.log.debug("--- GraphqlNode v" + vers + " ---");
RED.log.debug("GraphqlNode node: " + safeJSONStringify(node));
RED.log.trace("GraphqlNode config: " + safeJSONStringify(config));
node.endpoint = config.endpoint;
node.authorization = node.credentials.authorization
RED.log.debug("node.endpoint: " + node.endpoint);
RED.log.debug("node.authorization is specified")
}
RED.nodes.registerType("graphql-server", GraphqlNode, {
credentials: {
user: { type: "text" },
password: { type: "password" },
serviceTicket: { type: "password" },
authorization: { type: "password" }
}
});
function GraphqlExecNode(config) {
RED.nodes.createNode(this, config);
this.query = config.query;
this.template = config.template;
this.name = config.name;
this.varsField = config.varsField || "variables";
this.syntax = config.syntax || "mustache";
var node = this;
RED.log.debug("--- GraphqlExecNode ---");
//RED.log.debug('GraphqlExecNode node: ' + safeJSONStringify(node));
//RED.log.trace('GraphqlExecNode config: ' + safeJSONStringify(config));
// Retrieve the config node
node.graphqlConfig = RED.nodes.getNode(config.graphql);
var credentials = RED.nodes.getCredentials(config.graphql);
RED.log.trace("credentials: " + safeJSONStringify(credentials));
if (!node.graphqlConfig) {
this.error("invalid graphql config");
}
// This function returns true if you have a valid Ticket, false if you don't
function testTicket() {
// GET /user/{username}
RED.log.debug("--- test ticket ---");
axios({
method: "POST",
url:
node.graphqlConfig.endpoint +
"user/" +
node.graphqlConfig.credentials.user,
timeout: 20000,
headers: {
"x-auth-token": node.graphqlConfig.credentials.serviceTicket
}
// withCredentials: useCredentials
}).then(function(response) {
RED.log.debug("response:" + response);
});
}
function doLogin() {
node.status({
fill: "blue",
shape: "ring",
text: RED._("graphql.status.connecting")
});
RED.log.debug("--- Login (accept unauthorized) ---");
request(
{
url: node.graphqlConfig.endpoint,
method: "POST",
json: true,
timeout: 20000
},
function(error, response, body) {
if (response) {
switch (response.statusCode) {
case 200:
node.status({
fill: "green",
shape: "dot",
text: RED._("graphql.status.connected")
});
RED.log.debug("statusCode: " + response.statusCode);
RED.log.debug("response: " + safeJSONStringify(response));
RED.log.debug("body: " + safeJSONStringify(body));
RED.log.debug("serviceTicket: " + body.response.serviceTicket);
node.graphqlConfig.credentials.serviceTicket =
body.response.serviceTicket; // store service ticket
RED.log.debug(
"updated credentials (2): " +
safeJSONStringify(node.graphqlConfig.credentials)
);
RED.nodes.addCredentials(
node.graphqlConfig,
node.graphqlConfig.credentials
);
RED.log.debug("body: " + safeJSONStringify(body));
RED.log.debug("node.msg: " + safeJSONStringify(node.msg));
node.warn("Calling send with msg: " + safeJSONStringify(node.msg));
node.send([node.msg]);
break;
case 401: // token issues
RED.log.debug("401 response: " + safeJSONStringify(response));
if (response.body.response.errorCode) {
RED.log.debug(
"401 response.body.response.errorCode: " +
response.body.response.errorCode
);
switch (response.body.response.errorCode) {
case "RBAC": // token not recognized
errorMsg = RED._("graphql.errors.tokenExpLogin");
node.msg.payload = {
statusCode: response.statusCode,
errorCode: response.body.response.errorCode,
message: errorMsg,
detail: response.body.response.detail
};
node.error(errorMsg, node.msg);
node.close();
break;
case "INVALID_CREDENTIALS": // token not recognized
errorMsg = RED._("graphql.errors.badCreds");
//errorMsg = body.response.message;
node.status({
fill: "red",
shape: "dot",
text: errorMsg
});
node.msg.payload = {
statusCode: response.statusCode,
errorCode: response.body.response.errorCode,
message: errorMsg,
detail: response.body.response.detail
};
node.error(errorMsg, node.msg);
break;
default:
// other issue
errorMsg =
RED._("graphql.errors.error401") +
" " +
response.body.message;
node.status({
fill: "red",
shape: "dot",
text: errorMsg
});
node.msg.payload = {
statusCode: response.statusCode,
errorCode: response.body.response.errorCode,
message: errorMsg,
detail: response.body.response.detail
};
node.error(errorMsg, node.msg);
node.close();
}
} else {
node.status({ fill: "red", shape: "dot", text: errorMsg });
node.msg.payload = {
statusCode: response.statusCode,
message: errorMsg
};
node.error(
"401 error, response: " + safeJSONStringify(response),
node.msg
);
}
break;
case 403: // bad url, api version number
errorMsg = RED._("graphql.errors.badRest");
node.status({ fill: "red", shape: "dot", text: errorMsg });
// node.msg.payload = response;
node.warn("msg: " + safeJSONStringify(node.msg));
//node.msg.payload = response;
//delete node.msg.payload.body;
//delete node.msg.payload.headers;
//node.msg.response = {};
//node.msg.response = response;
//node.msg.response = { statusCode: 403 };
RED.log.debug("response: " + safeJSONStringify(response));
node.msg.payload = {
statusCode: response.statusCode,
message: errorMsg
};
node.warn("msg w/resp: " + safeJSONStringify(node.msg));
node.error(errorMsg, node.msg);
break;
case 500: // bad credentials
RED.log.debug(
"response (error 500): " + safeJSONStringify(response)
);
errorMsg = RED._("graphql.errors.badCreds");
node.status({ fill: "red", shape: "dot", text: errorMsg });
var longMsg = errorMsg;
if (response.body.response.message) {
longMsg += ", " + response.body.response.message;
}
node.msg.payload = {
statusCode: response.statusCode,
errorCode: response.body.response.errorCode,
message: longMsg
};
node.error(errorMsg, node.msg);
break;
default:
RED.log.debug("response: " + safeJSONStringify(response));
if (response) {
node.warn("errorCode: " + response.statusCode);
RED.log.debug("response.body: " + response.body);
RED.log.debug(
"type of response.body: " + typeof response.body
);
var responseJSON;
try {
responseJSON = JSON.parse(response.body);
RED.log.debug(
"responseJSON.response: " +
safeJSONStringify(responseJSON.response)
);
} catch (e) {
RED.log.error("error parsing response: " + response.body);
responseJSON = null;
}
if (responseJSON && responseJSON.response.message) {
node.error(
"error message: " + responseJSON.response.message
);
node.status({
fill: "red",
shape: "dot",
text: responseJSON.response.message
});
} else {
var status = responseJSON ? responseJSON.statusCode : null;
node.status({
fill: "red",
shape: "dot",
text: RED._("graphql.status.failedConn") + status
});
}
} // if response
node.msg.payload = response;
//node.error('default error, msg: ' + safeJSONStringify(node.msg), node.msg);
} // switch
} else {
node.warn("Failed connecting to Graphql");
// The response object is null
switch (error.code) {
case "ENOTFOUND":
errorMsg = RED._("graphql.errors.server");
node.status({ fill: "red", shape: "dot", text: errorMsg });
node.error(errorMsg, node.msg);
break;
case "ETIMEDOUT":
errorMsg = RED._("graphql.errors.timeout");
node.status({ fill: "red", shape: "dot", text: errorMsg });
node.error(errorMsg, node.msg);
break;
default:
node.status({
fill: "red",
shape: "dot",
text: RED._("graphql.status.failed") + " " + error.code
});
node.error("response empty, error: " + error, node.msg);
}
}
}
);
}
function callGraphQLServer(query, variables = {}) {
let headers = {}
if (node.graphqlConfig.authorization) {
headers["Authorization"] = "Bearer " + node.graphqlConfig.authorization // fix for Gitlab
}
//RED.log.debug('callGraphQLServer, node: ' + safeJSONStringify(node));
//RED.log.debug('callGraphQLServer, node.graphqlConfig.endpoint: ' + node.graphqlConfig.endpoint);
//RED.log.debug('callGraphQLServer, query: ' + query);
axios({
method: "POST",
url: node.graphqlConfig.endpoint,
timeout: 20000,
data: {
query: query,
variables: variables
},
headers
// withCredentials: useCredentials
})
.then(function(response) {
//RED.log.debug('response:' + safeJSONStringify(response, 1));
//RED.log.debug('response.data:' + safeJSONStringify(response.data));
//RED.log.debug('response.status:' + response.status);
switch (response.status) {
case 200:
node.status({
fill: "green",
shape: "dot",
text: RED._("graphql.status.success")
});
node.msg.payload.graphql = response.data.data; // make sure original msg is not overwritten
node.send(node.msg);
break;
default:
node.status({
fill: "red",
shape: "dot",
text: "status: " + response.status
});
node.msg.payload = {
statusCode: response.statusCode,
body: response.body
};
node.error(
"401 error, msg: " + safeJSONStringify(node.msg),
node.msg
);
node.send([null, node.msg]);
break;
}
})
.catch(function(error) {
RED.log.debug("error:" + error);
node.status({ fill: "red", shape: "dot", text: "error" });
node.msg.payload = { error };
node.error("error: " + error);
node.send([null, node.msg]);
});
}
//*********************************
// main function invoked on input
//*********************************
node.on("input", function(msg) {
RED.log.debug("--- on(input) ---");
RED.log.debug("msg: " + safeJSONStringify(msg));
node.msg = msg;
node.template = msg.template || node.template;
node.syntax = msg.syntax || node.syntax;
//RED.log.trace('node: ' + safeJSONStringify(node));
//RED.log.debug('node: ' + safeJSONStringify(node));
//RED.log.trace('config: ' + safeJSONStringify(config));
//RED.log.debug('config.query: ' + config.query);
var query;
if (node.syntax === "mustache") {
query = mustache.render(node.template, msg);
} else {
query = node.template;
}
var variables = msg[node.varsField] || {}
// Do we have a serviceTicket (in other words, have we successfully logged in)
if (!config.token) {
// no token so we're talking to a server that doesn't require a login
callGraphQLServer(query, variables);
} else if (!node.graphqlConfig.credentials.serviceTicket) {
RED.log.debug("No ticket, but we have a token so try to login");
doLogin(); // do the login
} else {
// we have a ticket
callGraphQLServer(query, variables);
}
});
node.on("close", function() {
RED.log.debug("--- closing node ---");
//RED.log.debug('node: ' + safeJSONStringify(node));
//RED.log.trace('config: ' + safeJSONStringify(config));
//RED.log.debug('pre credentials: ' + safeJSONStringify(node.graphqlConfig.credentials));
node.graphqlConfig.credentials.serviceTicket = ""; // store service ticket
RED.nodes.addCredentials(
node.graphqlConfig,
node.graphqlConfig.credentials
);
//RED.log.debug('post credentials: ' + safeJSONStringify(node.graphqlConfig.credentials))
});
}
RED.nodes.registerType("graphql", GraphqlExecNode);
};