-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
91 lines (80 loc) · 2.15 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
'use strict'
const httpMethods = require('./methods')
const Router = require('find-my-way')
class MoaRouter extends Router {
constructor (opts) {
super(opts)
let self = this
httpMethods.forEach(function (method) {
self[method] = function (path, handler, store) {
return self.on(method.toUpperCase(), path, handler, store)
}
})
}
lookupKoa (ctx, next) {
let req = ctx.req
// var res = ctx.res
let handle = this.find(req.method, sanitizeUrl(req.url))
if (!handle) return this._defaultKoaRoute(ctx, next)
ctx.params = handle.params
ctx.store = handle.store
return handle.handler(ctx, next)
}
lookupExpress (req, res, next) {
let handle = this.find(req.method, sanitizeUrl(req.url))
if (!handle) return this._defaultHttpRoute(req, res)
req.params = handle.params
req.store = handle.store
return handle.handler(req, res, next)
}
lookupHttp (req, res) {
let handle = this.find(req.method, sanitizeUrl(req.url))
if (!handle) return this._defaultHttpRoute(req, res)
return handle.handler(req, res, handle.params, handle.store)
}
_defaultKoaRoute (ctx, next) {
if (this.defaultRoute) {
this.defaultRoute(ctx, next)
}
}
_defaultHttpRoute (req, res) {
if (this.defaultRoute) {
this.defaultRoute(req, res)
} else {
res.statusCode = 404
res.end()
}
}
routes () {
let router = this
if (router.type === 'express') {
return function (req, res, next) {
router.lookupExpress(req, res, next)
}
} else if (router.type === 'koa') {
return function (ctx, next) {
router.lookupKoa(ctx, next)
}
} else {
return function (req, res) {
router.lookupHttp(req, res)
}
}
}
}
module.exports = function (opts) {
opts = opts || {}
if (opts && !opts.type) opts.type = 'koa'
let router = new MoaRouter(opts)
router.type = opts.type
return router
}
function sanitizeUrl (url) {
for (let i = 0, len = url.length; i < len; i++) {
let charCode = url.charCodeAt(i)
if (charCode === 63 || charCode === 35) {
return url.slice(0, i)
}
}
return url
}