-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
99 lines (83 loc) · 2.47 KB
/
app.js
File metadata and controls
99 lines (83 loc) · 2.47 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const express = require('express');
const bodyParser = require('body-parser');
const rp = require('request-promise-native');
const request = rp.defaults();
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
});
var app = express();
app.use(bodyParser.json());
app.post('/batch', async function(req, res){
const result = await execBatch(req.body.endpoint, req.body.payloads);
res.send(result);
});
async function execBatch(endpoint, payloads) {
var i = 0;
payloads.forEach(p => p.id = i++);
var result = {
stat: {
success: 0,
failed: 0
},
responses: []
};
await Promise.all(payloads.map(async (payload) => {
try {
const response = await exec(endpoint, payload, true);
result.stat.success++;
result.responses[payload.id] = {
"id": payload.id,
"status": "success",
"response": response
};
} catch (e) {
result.stat.failed++;
result.responses[payload.id] = {
"id": payload.id,
"status": "failed",
"response": e.message
};
}
return;
}));
return result;
}
async function exec(endpoint, payload, retry) {
try {
return await request({
method: endpoint.verb,
url: resolveUrl(endpoint.url, payload.path),
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
json: true,
body: payload.body
});
} catch (e) {
if (e.statusCode === 503 && retry) {
return await exec(endpoint, payload, false);
} else if (e.statusCode === 429) {
await wait(5000);
return await exec(endpoint, payload, true);
} else {
throw e;
}
}
}
function resolveUrl(url, paths) {
if (paths) {
for (let path of Object.keys(paths)) {
url = url.replace('{' + path + '}', paths[path]);
}
}
return url;
}
async function wait(timeout) {
return new Promise((resolve) => {
setTimeout(() => {
resolve()
}, timeout)
})
}
app.listen(5000);