/
APIRequest.js
68 lines (59 loc) · 2.32 KB
/
APIRequest.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
'use strict';
const FormData = require('form-data');
const https = require('https');
const { browser, UserAgent } = require('../util/Constants');
const fetch = require('node-fetch');
const AbortController = require('abort-controller');
if (https.Agent) var agent = new https.Agent({ keepAlive: true });
class APIRequest {
constructor(rest, method, path, options) {
this.rest = rest;
this.client = rest.client;
this.method = method;
this.route = options.route;
this.options = options;
let queryString = '';
if (options.query) {
// Filter out undefined query options
const query = Object.entries(options.query).filter(([, value]) => value !== null && typeof value !== 'undefined');
queryString = new URLSearchParams(query).toString();
}
this.path = `${path}${queryString && `?${queryString}`}`;
}
make() {
const API = this.options.versioned === false ? this.client.options.http.api :
`${this.client.options.http.api}/v${this.client.options.http.version}`;
const url = API + this.path;
let headers = {};
if (this.options.auth !== false) headers.Authorization = this.rest.getAuth();
if (this.options.reason) headers['X-Audit-Log-Reason'] = encodeURIComponent(this.options.reason);
if (!browser) headers['User-Agent'] = UserAgent;
if (this.options.headers) headers = Object.assign(headers, this.options.headers);
let body;
if (this.options.files) {
body = new FormData();
for (const file of this.options.files) if (file && file.file) body.append(file.name, file.file, file.name);
if (typeof this.options.data !== 'undefined') body.append('payload_json', JSON.stringify(this.options.data));
if (!browser) headers = Object.assign(headers, body.getHeaders());
} else if (this.options.data != null) { // eslint-disable-line eqeqeq
body = JSON.stringify(this.options.data);
headers['Content-Type'] = 'application/json';
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
return fetch(url, {
method: this.method,
headers,
agent,
body,
signal: controller.signal,
}).then(res => {
clearTimeout(timeout);
return res;
}, error => {
clearTimeout(timeout);
throw error;
});
}
}
module.exports = APIRequest;