forked from emkay/theodore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (84 loc) · 2.55 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
const qs = require('querystring')
const turbo = require('turbo-http')
const serverRouter = require('server-router')
const stringify = require('fast-safe-stringify')
const jsonParse = require('fast-json-parse')
class Theodore {
constructor (opts) {
this.opts = opts || {}
this.router = serverRouter()
}
get (route, handler) {
this.route('GET', route, handler)
}
post (route, handler) {
this.route('POST', route, handler)
}
put (route, handler) {
this.route('PUT', route, handler)
}
delete (route, handler) {
this.route('DELETE', route, handler)
}
route (method, route, handler) {
const _handler = (req, res, params) => {
const reqHeaders = req.getAllHeaders()
const type = reqHeaders.get('Content-Type')
res.send = (data, status, headers) => {
data = data || ''
data = Buffer.isBuffer(data) ? data : Buffer.from(data)
res.statusCode = status
headers = headers || {}
const keys = Object.keys(headers)
for (var i = 0; i <= keys.length; i++) {
res.setHeader(keys[i], headers[keys[i]])
}
res.setHeader('content-length', data.length)
res.write(data)
}
res.json = (json, status, headers) => {
const data = stringify(json)
headers = headers || {}
headers['content-type'] = headers['content-type'] || 'application/json'
res.send(data, status, headers)
}
const bodies = []
req.ondata = (body, start, length) => {
const part = body.slice(start, length + start).toString()
bodies.push(part)
}
req.onend = () => {
const b = bodies.join('')
switch (type) {
case 'application/json':
const parsedRes = jsonParse(b)
req.body = parsedRes.value || parsedRes.err
break
case 'application/x-www-form-urlencoded':
req.body = qs.parse(b)
break
case 'text/plain':
case 'text/html':
default:
req.body = b
break
}
handler(req, res, params)
}
}
this.router.route(method, route, _handler)
}
address () {
return (this.server && this.server.address())
}
listen (port, onlisten = () => {}, onrequest = (req, res) => {}) {
this.port = port || process.env.PORT || 8080
this.server = turbo.createServer(this.router.start())
this.server.listen(this.port, onlisten)
this.server.on('request', onrequest)
}
close () {
this.server.close()
}
}
module.exports = Theodore