/
httpRequestBuilder.js
95 lines (76 loc) · 2.66 KB
/
httpRequestBuilder.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
84
85
86
87
88
89
90
91
92
93
94
95
'use strict'
const methods = require('./httpMethods')
// this is a build request factory, that curries the build request function
// and sets the default for it
function requestBuilder (defaults) {
// these need to be defined per request builder creation, because of the way
// headers don't get deep copied
const builderDefaults = {
method: 'GET',
path: '/',
headers: {},
body: Buffer.alloc(0),
hostname: 'localhost',
setupRequest: reqData => reqData,
port: 80
}
defaults = Object.assign(builderDefaults, defaults)
// buildRequest takes an object, and turns it into a buffer representing the
// http request
return function buildRequest (reqData) {
// below is a hack to enable deep extending of the headers so the default
// headers object isn't overwritten by accident
reqData = reqData || {}
reqData.headers = Object.assign({}, defaults.headers, reqData.headers)
reqData = Object.assign({}, defaults, reqData)
reqData = reqData.setupRequest(reqData)
// for some reason some tests fail with method === undefined
// the reqData.method should be set to SOMETHING in this case
// cannot find reason for failure if `|| 'GET'` is taken out
const method = reqData.method
const path = reqData.path
const headers = reqData.headers
const body = reqData.body
let host = reqData.headers.host || reqData.host
if (!host) {
const hostname = reqData.hostname
const port = reqData.port
host = hostname + ':' + port
}
if (reqData.auth) {
const encodedAuth = Buffer.from(reqData.auth).toString('base64')
headers.Authorization = `Basic ${encodedAuth}`
}
if (methods.indexOf(method) < 0) {
throw new Error(`${method} HTTP method is not supported`)
}
const baseReq = [
`${method} ${path} HTTP/1.1`,
`Host: ${host}`,
'Connection: keep-alive'
]
let bodyBuf
if (typeof body === 'string') {
bodyBuf = Buffer.from(body)
} else if (Buffer.isBuffer(body)) {
bodyBuf = body
} else if (body) {
throw new Error('body must be either a string or a buffer')
}
if (bodyBuf && bodyBuf.length > 0) {
const idCount = reqData.idReplacement
? (bodyBuf.toString().match(/\[<id>\]/g) || []).length
: 0
headers['Content-Length'] = `${bodyBuf.length + (idCount * 27)}`
}
for (const [key, header] of Object.entries(headers)) {
baseReq.push(`${key}: ${header}`)
}
let req = Buffer.from(baseReq.join('\r\n') + '\r\n\r\n', 'utf8')
if (bodyBuf && bodyBuf.length > 0) {
req = Buffer.concat([req, bodyBuf])
}
return req
}
}
module.exports = requestBuilder