This repository has been archived by the owner on Aug 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreq.js
80 lines (65 loc) · 1.59 KB
/
req.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
const request = require('request-promise');
const chalk = require('chalk');
const Promise = require('bluebird');
const logger = require('./util/logger');
const withTimeout = Promise.promisify(function WithTimeout(timeout, reason, promise, cb) {
promise.then(res => {
cb(null, res);
}).catch(err => {
cb(err);
});
setTimeout(() => {
cb(new Error(`Request timeout ${reason}`));
}, timeout);
});
class Request {
constructor(url) {
this.baseUrl = url;
this.defaultHeaders = {};
this.timeout = 15000; // ms
}
/**
*
* @param {String} method
* @param {String} endpoint
* @param {Object} body
* @param {Object} headers
* @returns {Promise<void>}
*/
async request(method, endpoint, body = {}, headers = null) {
if (!headers) {
headers = this.defaultHeaders;
}
body = JSON.parse(JSON.stringify(body));
const options = {
method,
headers,
body,
url: this.baseUrl + endpoint,
json: true,
};
let log = logger.url(`${method} ${chalk.cyan(endpoint)}`);
try {
const result = await withTimeout(this.timeout, endpoint, request(options));
// TODO global validations maybe?
log.success();
return result;
} catch (e) {
log.error(e.message);
throw e;
}
}
async post(...args) {
return this.request('POST', ...args);
}
async get(...args) {
return this.request('GET', ...args);
}
async put(...args) {
return this.request('PUT', ...args);
}
async delete(...args) {
return this.request('DELETE', ...args);
}
}
module.exports = Request;