-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (53 loc) · 1.54 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
require('dotenv').config()
const http = require('http')
const parse = body => {
if(body){
return JSON.parse(body)
}
return null
}
const api = require('./api/api')
const getBody = req => new Promise((resolve) => {
const buffer = [];
req.on('data', chunk => {
buffer.push(chunk)
}).on('end', async () => {
const body = buffer.join('')
resolve(body)
})
})
const getHeaders = req => {
const obj = {}
for (let i = 0; i < req.rawHeaders.length; i = i+2) {
obj[req.rawHeaders[i]] = req.rawHeaders[i+1]
}
return obj
}
// parse Request Headers
const server = http.createServer()
server.on('request', async (req, res) => {
let {url, method} = req
console.log(`Received response from ${req.socket.localAddress}:${req.socket.localPort}\n url: ${url}`)
const handler = api[url + '/' + method]
if (!handler){
res.statusCode = 404
res.end(`404: Not Found`)
return
}
try {
const body = parse(await getBody(req))
let answer = await handler(body, getHeaders(req))
console.log("Server answer:", answer.body)
res.statusCode = answer.status
res.end(JSON.stringify(answer.body))
}
catch (err){
console.log(err)
res.statusCode = '500'
res.end("500: Internal Server Error")
}
})
server.listen(process.env.WEB_PORT)
console.log(`Server listening on port ${process.env.WEB_PORT}`)
process.once('SIGINT', () => server.close())
process.once('SIGTERM', () => server.close())