-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrapi.js
74 lines (65 loc) · 2.4 KB
/
strapi.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
// var axios = require('axios');
// var qs = require('qs');
var request = require('request');
module.exports = function(RED) {
"use strict";
// set this to true to spam your console with stuff.
var strapiDebug = true;
function strapiOut(n) {
RED.nodes.createNode(this,n);
var self = this;
this.strapiAPIURL = n.strapiAPIURL;
this.jwtToken = n.jwtToken || "";
var node = this;
this.on('input', function (msg) {
var strapiAPIURL = node.strapiAPIURL || msg.strapiAPIURL;
var jwtToken = node.jwtToken || msg.jwtToken;
var method = node.method || msg.method;
var id = msg.payload.id;
var data = msg.payload;
if (this.credentials && this.credentials.jwtToken) {
jwtToken = this.credentials.jwtToken;
}
if (strapiDebug) { node.log(JSON.stringify(data)); }
try {
var options = {};
options.method = method;
if(id){
options.uri = strapiAPIURL + '/' + id;
}else{
options.uri = strapiAPIURL;
}
node.log(options.uri);
if(method === 'get'){
options.query = JSON.stringify(data);
options.headers = {
'Authorization': 'Bearer '+jwtToken
};
}else if(method === 'post' || method === 'put' || method === 'delete'){
options.body = JSON.stringify(data);
options.headers = {
'Authorization': 'Bearer '+jwtToken,
'Content-Type': 'application/json',
'Content-Length': data.length
};
node.log(options.body);
}
request(options, function (err, res, body) {
if(err){
console.trace();
node.log(err,msg);
}else{
msg.payload = body;
msg.res = res;
self.send(msg);
}
});
}
catch (err) {
console.trace();
node.log(err,msg);
}
});
}
RED.nodes.registerType("strapi", strapiOut);
};