-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
83 lines (72 loc) · 1.95 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
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
/*
- Request Builder
- Make class based on http.request() function
- builder must provide HTTP method, URL, query component or URL, header params, and body
- to send, use invoke() method that returns promise
*/
import http from 'http'
/*
BUILDER CLASS
*/
class HTTPBuilder {
constructor(){
}
setHostPathAndPort(hostname,path,port){
this.hostname = hostname
this.path = path
this.port = port
return this
}
setMethod(method, postObject){
this.method = method
if(method == 'POST')
this.postData = JSON.stringify(postObject)
return this
}
setHeaders(type, length){
this.type = type
this.length = length
return this
}
build(){
this.options = {
hostname: this.hostname,
port: this.port,
path: this.path,
method: this.method,
headers: {
'Content-Type': this.type,
'Content-Length': this.length
}
}
}
invoke(){
return new Promise((resolve,reject)=>{
const req = http.request(this.options, (res)=>{
res.setEncoding('utf8')
res.on('data', (chunk)=>{
console.log(`Body: ${chunk}`)
})
res.on('end',()=>{
console.log(`No more data`)
})
})
req.on('error',(e)=>{
console.log(`problem: ${e.message}`)
reject()
})
if(this.method.toUpperCase() == 'POST')
req.write(this.postData)
req.end();
resolve()
})
}
}
let httpBuild = new HTTPBuilder()
httpBuild.setHostPathAndPort("www.google.com","/",80)
.setMethod('GET')
.setHeaders(null,null)
.build()
httpBuild.invoke()
.then(res=>console.log(`okay!: ${res}`))
.catch(err=> console.log(`not okay: ${err}`))