-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (59 loc) · 1.46 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
'use strict'
const url = require('url')
const assert = require('assert')
const routington = require('routington')
const series = require('fastseries')()
const HTTP_METHODS = [
'DELETE',
'GET',
'HEAD',
'PATCH',
'POST',
'PUT',
'OPTIONS'
]
const routify = function (baseRoutes = {}) {
const router = routington()
const middleware = []
Object.keys(baseRoutes).forEach(url => {
route(Object.assign({ url }, baseRoutes[url]))
})
const use = function use (url, subRouter) {
if (typeof url === 'function') {
middleware.push(url)
}
}
const route = function route (opts = {}) {
assert(opts.url, 'no url provided')
assert(opts.handler, `no handler provided for url: ${opts.url}`)
assert(opts.method, `no HTTP method provided`)
assert(
HTTP_METHODS.indexOf(opts.method) !== -1,
`${opts.method} is not a supported HTTP method`
)
const { url, handler, method } = opts
const node = router.define(url)[0]
node[method] = node[method] || []
node[method].push(handler)
}
const lookUp = function lookUp (req, res, next) {
const match = router.match(url.parse(req.url).pathname)
if (!match) {
// 404
return
}
const node = match.node
const handlers = node[req.method] || []
if (!handlers) {
// 405
return
}
series(null, [...middleware, ...handlers], { req, res }, next)
}
return {
route,
lookUp,
use
}
}
module.exports = routify