-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathRouter.js
250 lines (218 loc) · 5.94 KB
/
Router.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
const assert = require('assert')
const flatten = require('flatten')
const Routington = require('routington')
const methods = require('methods')
const compose = require('koa-compose')
const Methods = require('./Methods')
const {
isFunction,
isObject,
isString,
isUndefined,
noop
} = require('./lang')
const __MIDDLEWARE = Symbol()
const __ADD_ROUTE = Symbol()
const __PARSE_PATHS = Symbol()
const NODE_GAG = {
methods: new Methods(),
isGag: true
}
class Router {
/**
*
*/
constructor() {
this.methods = new Methods([
['OPTIONS']
])
this.trie = Routington()
this.loadRoutes()
}
/**
* @param {String} method
* @param {String|Array<String>} paths
* @param {...Function} [middleware]
* @returns {Router}
*/
addRoute(method, paths, ...middleware) {
// Is this router[verb](paths, middleware) signature?
if (isString(paths) || isString(paths[0])) {
this[__ADD_ROUTE](method, paths, middleware)
} else {
// Otherwise, signature is router[verb](middleware)
middleware.push(paths)
this[__ADD_ROUTE](method, undefined, middleware)
}
return this
}
/**
* @param {String} method
* @returns {Boolean}
*/
isImplementedMethod(method) {
return this.methods.has(method);
}
/**
*
*/
loadRoutes() {
for(let method of methods) {
this[method] = this.addRoute.bind(this, method.toUpperCase())
}
this.del = this.delete
}
/**
* @returns {Function}
*/
middleware() {
return this[__MIDDLEWARE].bind(this)
}
/**
* @param {...Function} middleware
* @returns {Router}
*/
use(...middleware) {
return this.addRoute('ANY', middleware)
}
/**
* @param {String} method
* @param {String|Array<String>|undefined} paths
* @param {Function|Array<Function>} middleware
*/
[__ADD_ROUTE](method, paths, middleware) {
// Take out all the falsey middleware
let stack = flatten(middleware).filter(Boolean)
stack.forEach(assertFunction)
/* istanbul ignore if */
if (!stack.length) {
return
}
if (isUndefined(paths)) {
this.methods.add(method, stack)
return
}
// For 501 Not Implemented support
this.methods.add(method)
if (method === 'GET') {
this.methods.add('HEAD')
}
let nodes = this[__PARSE_PATHS](paths);
for(let node of nodes) {
// Push the functions to the function stack
// and build the list of supported methods for this route
// for OPTIONS and 405 responses
node.methods.add(method, stack)
if (node.methods.has('GET')) {
node.methods.add('HEAD')
}
}
}
/**
* @param {String|Array<String>} paths
* @returns {Array}
*/
[__PARSE_PATHS](paths) {
let nodes = []
paths = flatten([paths]).filter(Boolean)
assert(paths.length, 'Route must have a path')
for(let path of paths) {
assert(isString(path), 'Paths must be strings: ' + path)
assert(path[0] === '/', 'Paths must start with a "/": ' + path)
for(let node of this.trie.define(path)) {
if (!nodes.includes(node)) {
node.methods = node.methods || new Methods([['OPTIONS']])
nodes.push(node)
}
}
}
assert(nodes.length, 'No routes defined. Something went wrong.')
return nodes
}
/**
* @param {Object} ctx
* @param {Function} next
* @return {Promise}
*/
[__MIDDLEWARE](ctx, next) {
let {method} = ctx
let match
try {
match = this.trie.match(ctx.request.path)
} catch (err) {
err.code = 'MALFORMEDURL'
throw err
}
let isMatched = isObject(match)
let node = isMatched ? match.node : NODE_GAG
node.methods = node.methods || NODE_GAG.methods
ctx.params = ctx.request.params = isMatched ? match.param : {}
let top = getMiddleware(this.methods, 'ANY') // router.use(fn)
let middle = getMiddleware(this.methods, method) // router[method](fn)
let bottom = getMiddleware(node.methods, method) // router[method](path, fn)
let stack = [
...top,
preMiddle.bind(this),
...middle,
preBottom.bind(this),
...bottom
]
let fn = compose(stack)
return fn(ctx, noop)
// ----------------
/**
* OPTIONS support
* we want to provide a default OPTIONS handler for any path
* so we set all the required headers and HTTP status here
* and we give middleware functions a chance to overwrite them
* then, in the `preBottom` function, we'll return this status
* (or the value it was overwritten with) if no middleware
* handles this path
*/
function preMiddle(ctx, goToMiddleMiddleware) {
if (method === 'OPTIONS') {
ctx.response.status = 204
ctx.response.set('Allow', this.methods.toString())
}
return goToMiddleMiddleware()
}
function preBottom(ctx, goToBottomMiddleware) {
// If no route match or no methods are defined, go to next middleware
if (node.isGag || !node.methods.size) {
return next()
}
// If there is no one middleware
// it's a 405 error
//
// normally we'd return a 405 here since no route handles this path
// but we provide a default OPTIONS handler
// we've set all of the necessary headers and HTTP statuses in the `preMiddle` function
if (!bottom.length && method !== 'OPTIONS') {
ctx.response.set('Allow', this.methods.toString())
ctx.response.status = 405
return
}
return goToBottomMiddleware()
}
}
}
/**
* @param {Function} fn
* @returns {Function}
*/
function assertFunction(fn) {
assert(isFunction(fn), 'all middleware must be functions')
return fn
}
/**
* @param {Methods} methods
* @param {String} method
* @returns {Array<Function>}
*/
function getMiddleware(methods, method) {
if (method === 'HEAD') {
return methods.hasMiddleware('HEAD') ? methods.get('HEAD') : methods.get('GET')
}
return methods.get(method)
}
module.exports = Router