/
202-example.js
81 lines (74 loc) · 2.18 KB
/
202-example.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
const axios = require('axios').default;
let baseUrl = "https://apps.runbuggy.com/testing-v2/api";
let config = {
headers: {
'Authorization': 'Bearer changeme'
},
};
let requestBody = {
"type": "BASIC",
"vehicleTransferOrders": [
{
"directions": {
"pickup": {
"address": "4884 E Butler Ave, Fresno, CA 93727"
},
"dropoff": {
"address": "10050 N Metro Pkwy E, Phoenix, AZ 85051"
}
},
"vehicle": {
"vin": "KL4CJHSB3EB688122"
}
}
]
};
let order = null;
axios.post(baseUrl + '/orders', requestBody, config)
.then(response => {
if (response.status === 201) {
//success
order = response.data;
}
if (response.status === 202) {
getPendingOrder(response.headers.location).then(r => console.log(order));
}
if (response.status === 400) console.error(response.data.errors)
}).catch(error => {
// handle error
console.error(error);
});
async function getPendingOrder(resourceLocation) {
let attemptsRemaining = 10;
while (order == null && attemptsRemaining > 0) {
console.log("checking order");
await timeout(5000);
axios.get(baseUrl + resourceLocation, config)
.then(async response => {
switch(response.data.status) {
case "created": {
order = response.data;
break;
}
case "error": {
console.error(response.data.errors);
attemptsRemaining = 0;
break;
}
default: {
attemptsRemaining--;
break;
}
}
}).catch(error => {
// handle error
console.error(error);
attemptsRemaining--;
});
}
}
async function timeout(delayMs) {
return new Promise((resolve, reject) => {
setTimeout(resolve, delayMs);
});
}