-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
63 lines (51 loc) · 1.43 KB
/
server.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
'use strict'
const { createServer } = require('http')
const path = require('path')
const serveHandler = require('serve-handler')
const { getResponse } = require('./lib')
const port = 8080
const assetPort = 8081
const host = 'localhost'
const config = {
title: 'Lambda@Edge Immutable Web App',
reportUri: 'https://httpbin.org/post',
api: 'https://httpbin.org'
}
const options = {
config: JSON.stringify(config),
origin: `http://${host}:${assetPort}`,
version: ''
}
const formatHeaders = headers => Object.assign.apply({},
Object.values(headers)
.map(v => v[0])
.map(({ key, value }) => ({ [key]: value }))
)
const assetServer = createServer((req, res) => {
const root = path.resolve(__dirname, 'dist')
serveHandler(req, res, { public: root })
})
const server = createServer((req, res) => {
const handleError = err => {
console.error(err)
res.writeHead(500)
res.end()
}
const handleResponse = response => {
const { status, body, bodyEncoding, headers } = response
res.writeHead(status, formatHeaders(headers))
if (!body) return res.end()
const data = Buffer.from(body, bodyEncoding)
res.end(data)
}
getResponse(req, options, (err, response) => {
try {
if (err) return handleError(err)
handleResponse(response)
} catch (error) {
handleError(error)
}
})
})
assetServer.listen(assetPort)
server.listen(port, () => { console.log(`http://${host}:${port}`) })