-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (46 loc) · 1.43 KB
/
index.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
'use strict'
const http = require('node:http')
class MyHttpRequest {
static instance() {
return new MyHttpRequest()
}
withUrl(url) {
this.url = url
return this;
}
withHttpMethod(httpMethod) {
this.method = httpMethod
return this;
}
async invoke() {
return new Promise((resolve, reject) => {
const urlParts = this.url.split('https://') || this.url.split('http://')
const hostAndParams = urlParts[1].split('/')
const options = {
hostname: hostAndParams[0],
port: 80,
path: hostAndParams[1] || '/',
method: this.method,
headers: this.method === 'POST' ? {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
} : {},
}
const req = http.request(options, (res) => {
resolve(res)
})
req.end()
req.on('error', () => {
console.error('Error while trying to do the http request. Aborting...')
reject(new Error('Error with the request'))
})
})
}
}
(async () => {
const response = await MyHttpRequest.instance()
.withUrl('https://www.google.com')
.withHttpMethod('GET')
.invoke()
console.log(response.statusCode)
})()