-
Notifications
You must be signed in to change notification settings - Fork 45
/
index.js
73 lines (58 loc) · 1.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
'use strict';
/**
* Module dependencies.
*/
const { pathToRegexp } = require('path-to-regexp');
const debug = require('debug')('koa-route');
const methods = require('methods');
methods.forEach(function(method){
module.exports[method] = create(method);
});
module.exports.del = module.exports.delete;
module.exports.all = create();
function create(method) {
if (method) method = method.toUpperCase();
return function(path, fn, opts){
const keys = [];
const re = pathToRegexp(path, keys, opts);
debug('%s %s -> %s', method || 'ALL', path, re);
const createRoute = function(routeFunc) {
return function (ctx, next){
// method
if (!matches(ctx, method)) return next();
// path
const m = re.exec(ctx.path);
if (m) {
const args = m.slice(1).map(decode);
ctx.routePath = path;
debug('%s %s matches %s %j', ctx.method, path, ctx.path, args);
args.unshift(ctx);
args.push(next);
return Promise.resolve(routeFunc.apply(ctx, args));
}
// miss
return next();
}
};
if (fn) {
return createRoute(fn);
} else {
return createRoute;
}
}
}
/**
* Decode value.
*/
function decode(val) {
if (val) return decodeURIComponent(val);
}
/**
* Check request method.
*/
function matches(ctx, method) {
if (!method) return true;
if (ctx.method === method) return true;
if (method === 'GET' && ctx.method === 'HEAD') return true;
return false;
}