Good afternoon guys,
How can I create a variable in NodeJS / JS where I would return a value only to be used multiple times throughout the program?
Exemplifying my problem:
I have to log in to a platform and then send data to it. When I log in, it returns a "key" that I can send the data with.
I will have to send data several times and login will always be the same, based on that, would it be possible to have a variable that will receive the function that only logs the key?
The code I initially tried did not use promises as can be seen below:
var retornaToken = restclient.post(url, args, function (data, res) {
if(res.statusCode === 200){
console.log("Conectou com sucesso");
return data.chave;
} else {
console.log("Opa, não conectou");
return false;
}
});
module.exports = {
retornaToken : retornaToken
};
However, in another class when calling the returnToken, the return I get is the ClientRequest and not the token.
So I started using promises using the package Q
of the node, however, I still have a problem.
I've already created a function to log in using promises
function realizaLogin(user, pass) {
var defer = q.defer();
var args = {
headers: {"Content-Type": "application/json"},
data: {username: user, password: pass}
};
restclient.post(url, args, function (data, res) {
if (res.statusCode !== 200) {
console.log("Opa, deu ruim");
defer.reject("Deu ruim!");
}
else {
console.log("Conectou com sucesso");
defer.resolve(data);
}
//console.log("Tudo OK!\n");
//console.log(data.access_token);
});
return defer.promise;
}
var login = realizaLogin(user, pass);
module.exports = { login : login };
But when I tried to call login
(which is exported) as follows
var login = require('./controller');
var token = login.login; // ou var token = login;
console.log(token);
I get the following return on the console:
{ state: 'pending' }
Conectou com sucesso
I've already tried to use Q.all
to see if it expects to log in, creating another class and turning the realizLogin into an array of promises but without success as well.
Does anyone know how to export only the key to avoid having to log in every time I have to send data to the server?