-
Notifications
You must be signed in to change notification settings - Fork 2
/
7.2-request-builder.js
84 lines (70 loc) · 1.69 KB
/
7.2-request-builder.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
82
83
import { request } from 'https';
import { URL } from 'url';
class BuildRequest {
constructor() {
this.body = '';
}
setMethod(method) {
if (!method) {
throw new Error('Provided wrong http method');
}
this.method = method;
return this;
}
setUrl(urlStr) {
this.url = new URL(urlStr);
return this;
}
setQueryParams(query) {
Object.entries(query).forEach(([key, val]) => this.url.searchParams.set(key, val));
return this;
}
setHeaders(headers) {
this.headers = headers;
return this;
}
setBody(body) {
this.body = JSON.stringify(body) || '';
return this;
}
validateRequestParams() {
return this.url && this.method;
}
setPort(port) {
this.port = port;
return this;
}
invoke() {
const options = {
host: this.url.host,
path: `${this.url.pathname}?${this.url.searchParams.toString()}`,
method: this.method,
headers: {
Accept: 'application/json',
...this.headers,
}
};
if (!this.validateRequestParams()) throw Error('Please provide at least method and url');
return new Promise((resolve, reject) => {
const req = request(options, (res) => {
let resAccum = '';
res.on('data', (chunk) => {
resAccum += chunk.toString();
});
res.on('end', () => resolve(JSON.parse(resAccum)));
res.on('error', reject);
});
req.on('error', reject);
req.write(this.body);
req.end();
})
}
}
new BuildRequest()
.setMethod('GET')
.setUrl('https://api.urbandictionary.com/v0/define')
.setQueryParams({ term: 'wat' })
.invoke()
.then((res) => {
console.log('REQUEST finished', res);
})