-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
97 lines (77 loc) · 2.5 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
const compile = require('path-to-regexp').match
const flatten = require('lodash/flattenDeep')
const METHODS = require('http').METHODS
const unique = require('lodash/uniq')
module.exports = function (options) {
options = options || {}
return function (path, fn) {
const match = compile(path, options)
// app.use(route(:path, function () {}))
if (Array.isArray(fn) || typeof fn === 'function') {
if (arguments.length > 2) fn = [].slice.call(arguments, 1)
if (Array.isArray(fn)) fn = compose(flatten(fn))
return function (ctx, next) {
const result = match(ctx.request.path)
if (!result) return next()
ctx.params = result.params
return fn(ctx, next)
}
}
// app.use(route(:path).get(function () {}).post(function () {}))
return newRoute(match)
}
}
function newRoute (match) {
const route = function (ctx, next) {
const dispatcher = route.dispatcher || (route.dispatcher = createDispatcher(route))
return dispatcher(ctx, next)
}
route.match = match
route.methods = Object.create(null)
METHODS.forEach((method) => {
route[method] =
route[method.toLowerCase()] = function (fn) {
if (arguments.length > 2) fn = [].slice.call(arguments, 1)
if (Array.isArray(fn)) fn = compose(flatten(fn))
if (typeof route.methods[method] === 'function') throw new Error(`Method ${method} is already defined for this route!`)
route.methods[method] = fn
return route
}
})
return route
}
function createDispatcher (route) {
const match = route.match
const controllers = route.methods
if (!controllers.HEAD && controllers.GET) controllers.HEAD = controllers.GET
const ALLOW = unique(['OPTIONS'].concat(Object.keys(route.methods))).join(',')
return function (ctx, next) {
const result = match(ctx.request.path)
if (!result) return next()
ctx.params = result.params
ctx.allow = ALLOW
const method = ctx.method
// handle OPTIONS
if (method === 'OPTIONS') {
ctx.set('Allow', ALLOW)
if (controllers.OPTIONS) return controllers.OPTIONS(ctx)
ctx.status = 204
return
}
// handle other methods
const fn = controllers[method]
if (fn) return fn(ctx, next)
// 405
ctx.set('Allow', ALLOW)
ctx.status = 405
}
}
function compose (fns) {
return function (ctx, next) {
let rn = fns[fns.length - 1].bind(null, ctx, next)
for (let n = fns.length - 2; n >= 0; n--) {
rn = fns[n].bind(null, ctx, rn)
}
return rn()
}
}