-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
277 lines (226 loc) · 7.84 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
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*!
* koa-isomorphic-router
*
*
* Copyright(c) 2021 Imed Jaberi
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
const FastRouter = require('trek-router')
const koaCompose = require('koa-compose')
const hashlruCache = require('hashlru')
/**
* Symbol(s) used to set some attributes and methods as private.
*
* @api private
*/
// attributes.
const fastRouter = Symbol('@@fastRouter$$')
const METHODS = Symbol('@@METHODS$$')
const throws = Symbol('@@throws$$')
const methodNotAllowed = Symbol('@@methodNotAllowed$$')
const notImplemented = Symbol('@@notImplemented$$')
const routePrefix = Symbol('@@routePrefix$$')
const routePath = Symbol('@@routePath$$')
const middlewaresStore = Symbol('@@middlewaresStore$$')
const cache = Symbol('@@cache$$')
const allowHeaderStore = Symbol('@@allowHeaderStore$$')
// methods.
const on = Symbol('@@on$$')
const getAllowHeaderTuple = Symbol('@@getAllowHeaderTuple$$')
const normalizePath = Symbol('@@normalizePath$$')
/**
* Fast and isomorphic Router for Koa.js.
*
* @api public
*/
class Router {
// init Router.
constructor (options = {}) {
// init attributes.
this[fastRouter] = new FastRouter()
this[METHODS] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']
this[throws] = typeof options.throw === 'boolean' ? options.throw : false
this[methodNotAllowed] = options.methodNotAllowed
this[notImplemented] = options.notImplemented
this[routePrefix] = typeof options.prefix === 'string' ? options.prefix : '/'
this[routePath] = undefined
this[middlewaresStore] = []
this[cache] = hashlruCache(1000)
this[allowHeaderStore] = [] // [{ path: '', methods: [] }]
}
// normalize the path by remove all trailing slash.
[normalizePath] (path) {
path = path.replace(/\/\/+/g, '/')
if (path !== '/' && path.slice(-1) === '/') {
path = path.slice(0, -1)
}
return path
}
// get allow header for specific path.
[getAllowHeaderTuple] (path) {
return this[allowHeaderStore].find(allow => allow.path === path)
}
// register route with specific method.
[on] (method, path, ...middlewares) {
// handle the path arg when passed as middleware.
if (typeof path !== 'string') {
middlewares = [path, ...middlewares]
path = this[routePath]
}
// normalize the path.
path = this[normalizePath](this[routePrefix] + path)
// register path with method(s) to re-use as allow header filed.
// allow header.
const allow = this[getAllowHeaderTuple](path)
// stock to allow header store with unique val array.
this[allowHeaderStore] = [...new Map([
...this[allowHeaderStore],
{ path, methods: !allow ? [method] : [...new Set([...allow.methods, method])] }
].map(item => [item.path, item])).values()]
// register to route to the trek-router stack.
this[fastRouter].add(method, path, koaCompose(middlewares))
// give access to other method after use the current one.
return this
}
// register route with get method.
get (path, ...middlewares) {
return this[on]('GET', path, ...middlewares)
}
// register route with post method.
post (path, ...middlewares) {
return this[on]('POST', path, ...middlewares)
}
// register route with put method.
put (path, ...middlewares) {
return this[on]('PUT', path, ...middlewares)
}
// register route with patch method.
patch (path, ...middlewares) {
return this[on]('PATCH', path, ...middlewares)
}
// register route with delete method.
delete (path, ...middlewares) {
return this[on]('DELETE', path, ...middlewares)
}
// `router.all()` method >> register route with all methods.
all (path, ...middlewares) {
return this[on](this[METHODS], path, ...middlewares)
}
// add prefix to route path.
prefix (prefix) {
this[routePrefix] = typeof prefix === 'string' ? prefix : this[routePrefix]
return this
}
// give access to write once the path of route.
route (path) {
// update the route-path.
this[routePath] = path
// give access to other method after use the current one.
return this
}
// use given middleware, if and only if, a route is matched.
use (...middlewares) {
// check middlewares.
if (middlewares.some(mw => typeof mw !== 'function')) {
throw new TypeError('".use()" requires a middleware(s) function(s)')
}
// add the current middlewares to the store.
this[middlewaresStore] = [...this[middlewaresStore], ...middlewares]
// give access to other method after use the current one.
return this
}
// router middleware which handle a route matching the request.
routes () {
return async (ctx) => {
// normalize the path.
const path = this[normalizePath](ctx.path)
// ignore favicon request.
// src: https://github.com/3imed-jaberi/koa-no-favicon/blob/master/index.js
if (/\/favicon\.?(jpe?g|png|ico|gif)?$/i.test(ctx.path)) { return }
// init route matched var.
let route
// have slashs ~ solve trailing slash.
if (path !== ctx.path) {
ctx.response.status = 301
ctx.redirect(`${path}${ctx.search}`)
return
}
// generate the cache key.
const requestCacheKey = `${ctx.method}_${ctx.path}`
// get the route from the cache.
route = this[cache].get(requestCacheKey)
// if the current request not cached.
if (!route) {
// find route inside the routes stack.
route = this[fastRouter].find(ctx.method, ctx.path)
// put the matched route inside the cache.
this[cache].set(requestCacheKey, route)
}
// extract the handler func and the params array.
const [handler, routeParams] = route
// check the handler func isn't defined.
if (!handler) {
// warning: need more work with trek-router for support 'param' and 'match-any' route.
// get methods exist on allow header.
const allowHeaderFiled = this[getAllowHeaderTuple](path)
if (allowHeaderFiled) {
// if `OPTIONS` request responds with allowed methods.
if (ctx.method === 'OPTIONS') {
ctx.status = 204
ctx.set('Allow', allowHeaderFiled.methods.join(', '))
ctx.body = ''
return
}
// support 405 method not allowed.
if (this[throws]) {
throw typeof this[methodNotAllowed] === 'function'
? this[methodNotAllowed]()
: (() => {
const notAllowedError = new Error(`"${ctx.method}" is not allowed in "${ctx.path}".`)
notAllowedError.statusCode = 405
return notAllowedError
})()
}
ctx.status = 405
ctx.set('Allow', allowHeaderFiled.methods.join(', '))
ctx.body = `"${ctx.method}" is not allowed in "${ctx.path}".`
return
}
// suport 501 path not implemented.
if (this[throws]) {
throw typeof this[notImplemented] === 'function'
? this[notImplemented]()
: (() => {
const notImplError = new Error(`"${ctx.path}" not implemented.`)
notImplError.statusCode = 501
return notImplError
})()
}
ctx.status = 501
ctx.set('Allow', '')
ctx.body = `"${ctx.path}" not implemented.`
return
}
// check if the route params isn't empty array.
if (routeParams.length > 0) {
// parse the params if exist.
const params = {}
routeParams.forEach(({ name: key, value }) => { params[key] = value })
// append params to ctx and ctx.request.
ctx.params = ctx.request.params = params
}
// wait to all middlewares stored by the `use` method.
await Promise.all(this[middlewaresStore])
// wait the handler.
await handler(ctx)
}
}
}
/**
* Expose `Router`.
*/
module.exports = Router