var axios = require("axios").default;
var qs = require("qs");
module.exports = function (RED) {
let ISP_HOSTNAME=process.env.ISP_HOSTNAME;
---------> post call to return token.
const sendPostRequest = async (clientId, clientSecret) => {
const data = qs.stringify({
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret
})
const headers = {
'content-type': 'application/x-www-form-urlencoded'
}
const res = await axios.post(`https://mytokenurl`, data, headers);
return res.data.access_token;
}
function GetMachineLiveSpeedNode(config) {
RED.nodes.createNode(this, config);
var node = this;
let machineId="";
let token = "";
this.GetAuthentication = RED.nodes.getNode(config.GetAuthentication);
this.clientId = this.GetAuthentication.clientId;
this.clientSecret = this.GetAuthentication.clientSecret;
sendPostRequest(this.clientId, this.clientSecret) ----------> called when node is initial loaded in flow
.then((response) => {
token = response;
console.log("token inside : "+token);
}).catch((err) => {
console.log(err);
})
node.on('input', function (msg) {
machineId = msg.payload.machineId; ------------> machineId(20 plus in number ) coming from previous node
sendPostRequest(this.clientId, this.clientSecret) -----------> called multiple times on basis of number of machine Id passed
.then((response) => {
token = response;
console.log("token inside : "+token);
}).catch((err) => {
console.log(err);
})
let url = `https://${ISP_HOSTNAME}/someurlcontent/${machineId}/againsomeurlcontent`;
axios.get(url, { headers: { "Authorization": `Bearer ${token}` } })
.then((response)=>{
msg.payload=response.data;
node.send(msg);
}).catch((err)=>{
node.send(err);
})
});
}
RED.nodes.registerType("GetMachineLiveSpeed", GetMachineLiveSpeedNode);
}
Hi All,
above is my code, it is working but not the appropriate way of coding. so please review and guide.
I am confused that where to put my api calls so as to get the perfect output.
- I want that I make post call to get accesstoken one time only, and then make another get call with that access token and machineId as parameter to get response for mutiple machineId passed in input event of node.
- And my accesstoken expires in 30 min, so want to get new access token with help of refreshtoken.
Please help me on this.