-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (48 loc) · 1.52 KB
/
index.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
const dotenv = require('dotenv');
const jwt_decode = require('jwt-decode');
const fetch = require('node-fetch');
dotenv.config();
let token = null;
const baseUrl = 'https://cdn.emnify.net/api/v1/';
async function getValidAuthToken(){
let decodedToken = token == null ? null : jwt_decode(token); // If token exist, check whether it is valid
let currentDate = new Date();
if (decodedToken == null || decodedToken.exp * 1000 < currentDate.getTime()){
token = await getNewAuthToken(); // if no token exist or token is not valid, get new token
}
return token;
}
async function getNewAuthToken(){
return fetch(`${baseUrl}authenticate`, {
method: 'POST',
headers: {
"accept": "application/json",
"Content-Type": "application/json"
},
body: `{\"application_token\":\"${process.env.APP_TOKEN}\"}` // Enter your application token in place of ${process.env.APP_TOKEN}
})
.then(result => result.json())
.then(result => {
console.log("Your token is : "+result.auth_token);
return result.auth_token;
})
}
function getDeviceStatus(){
fetch(`${baseUrl}endpoint`, {
method: 'GET',
headers: {
"accept": "application/json",
"Authorization": `Bearer ${token}`
}
})
.then(result => result.json())
.then(result => {
console.log(result)
})
}
async function app(){
token = await getValidAuthToken();
// Make API Call
getDeviceStatus();
}
app();