forked from nathancahill/aws-serverless-micro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
195 lines (161 loc) · 5.09 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
const url = require('url')
const { ServerResponse } = require('http')
const { Stream } = require('stream')
const { readable } = require('is-stream')
const IncomingMessage = require('./IncomingMessage')
const getEventBody = event =>
Buffer.from(event.body, event.isBase64Encoded ? 'base64' : 'utf8')
const getPathWithQueryStringParams = event =>
url.format({
pathname: event.path,
query: {
...event.multiValueQueryStringParameters,
...event.queryStringParameters,
},
})
const mapApiGatewayEventToHttpRequest = event => {
const path = getPathWithQueryStringParams(event)
let req = new IncomingMessage()
const eventHeaders = { ...event.headers }
if (event.body) {
const buffer = getEventBody(event)
req.push(buffer)
req.push(null)
if (!eventHeaders['Content-Length']) {
eventHeaders['Content-Length'] = Buffer.byteLength(buffer)
}
} else {
req.push('')
req.push(null)
}
let headers = []
Object.keys(eventHeaders).forEach(k => {
headers.push(k)
headers.push(event.headers[k])
})
req._addHeaderLines(headers)
if (event.requestContext && event.requestContext.protocol) {
// eslint-disable-next-line no-unused-vars
const [_v, major, minor] = event.requestContext.protocol.split(/\/|\./g)
req.httpVersion = `${major}.${minor}`
req.httpVersionMajor = Number(major)
req.httpVersionMinor = Number(minor)
}
req.url = path
req.method = event.httpMethod
return req
}
const streamToString = stream => {
const chunks = []
return new Promise((resolve, reject) => {
stream.on('data', chunk => chunks.push(chunk))
stream.on('error', reject)
stream.on('end', () => {
resolve(chunks.join(''))
})
})
}
module.exports = mod => async event => {
const req = mapApiGatewayEventToHttpRequest(event)
const mockRes = new ServerResponse({ method: req.method })
let func = mod
if (mod && typeof mod === 'object') {
func = await mod.default
}
if (typeof func !== 'function') {
throw new Error('Expected a function.')
}
let endOutput
let endEncoding
const response = new Promise(resolve => {
mockRes.end = (data, encoding) => {
endOutput = data
endEncoding = encoding
resolve()
}
})
let obj
try {
obj = await func(req, mockRes)
} catch (errorObj) {
mockRes.statusCode = errorObj.statusCode || errorObj.status
return {
statusCode: mockRes.statusCode || 500,
headers: mockRes.getHeaders(),
body: errorObj.statusCode
? errorObj.message
: 'Internal Server Error',
}
}
if (obj === undefined) {
await response
}
let body = ''
if (mockRes.output.length) {
// eslint-disable-next-line no-unused-vars
const [headerString, _n, ...bodyBuffers] = mockRes.output
if (headerString.includes('chunked')) {
for (var i = 0; i < bodyBuffers.length; i = i + 4) {
body =
body + bodyBuffers[i].toString(mockRes.outputEncodings[i])
}
} else {
// eslint-disable-next-line no-unused-vars
const [headers, ...bodyStrings] = headerString.split('\r\n\r\n')
body = body + bodyStrings.join('\r\n\r\n')
}
}
if (endOutput) {
body = body + endOutput.toString(endEncoding || 'utf8')
}
if (body) {
return {
statusCode: mockRes.statusCode || 200,
headers: mockRes.getHeaders(),
body,
}
}
if (obj === null) {
return {
statusCode: 204,
headers: mockRes.getHeaders(),
body: '',
}
}
if (Buffer.isBuffer(obj)) {
if (!mockRes.getHeader('Content-Type')) {
mockRes.setHeader('Content-Type', 'application/octet-stream')
}
mockRes.setHeader('Content-Length', obj.length)
return {
statusCode: mockRes.statusCode || 200,
headers: mockRes.getHeaders(),
body: obj.toString('utf8'),
}
}
if (obj instanceof Stream || readable(obj)) {
if (!mockRes.getHeader('Content-Type')) {
mockRes.setHeader('Content-Type', 'application/octet-stream')
}
return {
statusCode: mockRes.statusCode || 200,
headers: mockRes.getHeaders(),
body: await streamToString(obj),
}
}
if (typeof obj === 'object' || typeof obj === 'number') {
if (!mockRes.getHeader('Content-Type')) {
mockRes.setHeader('Content-Type', 'application/json; charset=utf-8')
}
return {
statusCode: mockRes.statusCode || 200,
headers: mockRes.getHeaders(),
body: JSON.stringify(obj),
}
}
return {
statusCode: mockRes.statusCode || 200,
headers: mockRes.getHeaders(),
body: obj || '',
}
}