-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
45 lines (34 loc) · 1.11 KB
/
index.js
File metadata and controls
45 lines (34 loc) · 1.11 KB
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
const http = require('http')
const url = require('url')
const { port } = require('./config')
const handlers = require('./handlers')
const notFoundHandler = (callback) => {
callback(404)
}
const sendResponse = (res, statusCode = 200, payload = {}) => {
const payloadString = JSON.stringify(payload)
res.setHeader('Content-Type', 'application/json')
res.writeHead(statusCode)
// Only send the payload if it's not an empty object
if (payloadString !== '{}') {
res.end(payloadString)
} else {
res.end()
}
}
const unifiedServer = (req, res) => {
const parsedUrl = url.parse(req.url, true)
const path = parsedUrl.pathname
const trimmedPath = path.replace(/^\/+|\/+$/g, '')
const method = req.method.toLowerCase()
if (handlers[trimmedPath] && handlers[trimmedPath][method]) {
const handler = handlers[trimmedPath][method]
handler(sendResponse.bind(null, res))
} else {
notFoundHandler(sendResponse.bind(null, res))
}
}
const httpServer = http.createServer(unifiedServer)
httpServer.listen(port, () => {
console.log(`The server is listening for http traffic on port ${port}`)
})