-
Notifications
You must be signed in to change notification settings - Fork 0
/
oneapi.js
171 lines (141 loc) · 4.03 KB
/
oneapi.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
import { randomUUID } from 'crypto'
import http from 'http'
export class Route {
template = null
handler = null
constructor(template, handler) {
this.template = template
this.handler = handler
}
validate(req) {
const body = req.body
if (!this.template) {
return false
}
for (const key in this.template) {
if (this.template[key] !== body[key]) {
return false
}
}
return true
}
async handle(json, req, res) {
return await this.handler(json, req, res)
}
}
class FakeConsole {
log(...args) { }
error(...args) { }
}
export class OneApi {
static DefaultPort = 80
id = null
server = null
routes = []
middleware = []
defaultRoute = null
logger = console
constructor(debug = false) {
if (!debug) {
this.logger = new FakeConsole()
}
this.id = randomUUID()
this.server = http.createServer((req, res) => {
this.resolve(this, req, res)
})
this.logger.log(`Created OneApi instance with id ${this.id}`)
}
use(middleware) {
if (middleware == null) {
throw new Error('Cannot add null middleware')
}
if (!(middleware instanceof Function)) {
throw new Error('Middleware must be a function')
}
this.middleware.push(middleware)
}
add(template, handler) {
if (template == null || handler == null) {
throw new Error('Cannot add null route')
}
if (Object.keys(template).length === 0) {
throw new Error('Route template cannot be empty object. Use default route instead.')
}
if (!(handler instanceof Function)) {
throw new Error('Route handler must be a function')
}
this.routes.push(new Route(template, handler))
}
default(handler) {
if (handler == null) {
throw new Error('Cannot add null route')
}
this.defaultRoute = new Route(null, handler)
}
static async awaitBody(req) {
return new Promise((resolve, reject) => {
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
resolve(body)
})
})
}
async resolve(api, req, res) {
res.setHeader('Content-Type', 'application/json')
// Parse body
try {
req.body = JSON.parse(await OneApi.awaitBody(req))
}
catch (e) {
res.end(JSON.stringify({ error: 'invalid_json' }))
this.logger.log("Invalid JSON received")
return
}
// Check body
if (req.body == null) {
res.end(JSON.stringify({ error: 'empty_json' }))
this.logger.log("Empty JSON received")
return
}
function send(json) {
res.end(JSON.stringify(json))
}
// Apply middleware
for (const middleware of api.middleware) {
const resp = await middleware(req.body, req, res)
this.logger.log(req.body)
if (resp) {
send(resp)
return
}
}
for (const route of api.routes) {
if (route.validate(req)) {
const resp = await route.handle(req.body, req, res)
if (resp) {
send(resp)
}
return
}
}
if (api.defaultRoute) {
const resp = await api.defaultRoute.handle(req.body, req, res)
if (resp) {
send(resp)
}
return
}
res.end(JSON.stringify({ error: 'no_route' }))
}
listen(...args) {
if (args.length === 0) {
args.push(OneApi.DefaultPort)
}
this.server.listen(...args)
this.logger.log(`Listening on port ${args[0]}`)
return this.server
}
}