-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (68 loc) · 2.01 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
const fs = require('fs')
const url = require('url')
const http = require('http')
const https = require('https')
const { StringDecoder } = require('string_decoder')
const config = require('./config')
const handlers = require('./lib/handlers')
const data = require('./lib/data')
const helpers = require('./lib/helpers')
const httpServer = http.createServer(function (req, res) {
myServer(req, res)
})
httpServer.listen(config.httpPort, () => {
console.log(`Listening on port ${config.httpPort}`)
})
const httpsServer = https.createServer({
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
}, (req, res) => {
myServer(req, res)
})
httpsServer.listen(config.httpsPort, () => {
console.log(`Listening on port ${config.httpsPort}`)
})
const myServer = function (req, res) {
//const parsedUrl = new URL(req.url, `http://${req.headers.host}/`)
const parsedUrl = url.parse(req.url, true)
const path = parsedUrl.pathname
const trimmedPath = path.replace(/^\/+|\/+$/g, '')
const queryStringObject = parsedUrl.query
const method = req.method.toLowerCase()
const headers = req.headers
const decoder = new StringDecoder()
let buffer = ''
req.on('data', (data) => {
buffer += decoder.write(data)
})
req.on('end', () => {
buffer += decoder.end()
const handling = typeof (router[path]) !== 'undefined' ? router[path] : handlers.notFound
const data = {
trimmedPath,
queryStringObject,
method,
headers,
payload: helpers.parseJsonToObject(buffer)
}
handling(data, (statusCode, payload) => {
statusCode = typeof (statusCode) === 'number' ? statusCode : 200
payload = typeof (payload) === 'object' ? payload : {}
const payloadString = JSON.stringify(payload)
res.setHeader('Content-Type', 'application/json')
res.writeHead(statusCode)
res.end(payloadString)
return
})
console.log({
time: new Date().toISOString(),
url: req.url,
method: req.method.toLowerCase(),
body_size: buffer.length
})
})
}
const router = {
'/ping': handlers.ping,
'/users': handlers.users
}