koa-router layer.js

Koa-Router 源码解析

Talk is cheap, show me the code

koa-router

打开源码目录,就涉及两个重要文件,layer.js和router.js,分别对应Router和Layer对象

Layer对象是对单个路由的管理,其中包含的信息有路由路径(path)、路由请求方法(method)和路由执行函数(middleware),并且提供路由的验证以及params参数解析的方法。

Router对象则是对所有注册路由的统一处理,并且它的API是面向开发者的。

分析koa-router的实现原理可以从以下几个方面入手:

  • Layer对象的实现
  • 路由注册
  • 路由匹配
  • 路由执行流程

Layer

Layer对象主要管理单个路由,是每个路由的最新处理单元。

先看一下Layer对象声明的源码。

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
/**
* Initialize a new routing Layer with given `method`, `path`, and `middleware`.
*
* @param {String|RegExp} path Path string or regular expression.
* @param {Array} methods Array of HTTP verbs.
* @param {Array} middleware Layer callback/middleware or series of.
* @param {Object=} opts
* @param {String=} opts.name route name
* @param {String=} opts.sensitive case sensitive (default: false)
* @param {String=} opts.strict require the trailing slash (default: false)
* @returns {Layer}
* @private
*/
function Layer(path, methods, middleware, opts) {
this.opts = opts || {};
// 支持路由别名
this.name = this.opts.name || null;
this.methods = [];
this.paramNames = [];
// 将路由执行函数保存在stack中,支持输入多个处理函数
this.stack = Array.isArray(middleware) ? middleware : [middleware];
// HEAD请求头部信息与GET一致,这里就一起处理了。
methods.forEach(function(method) {
var l = this.methods.push(method.toUpperCase());
if (this.methods[l-1] === 'GET') {
this.methods.unshift('HEAD');
}
}, this);
// ensure middleware is a function 确保中间件类型正确
this.stack.forEach(function(fn) {
var type = (typeof fn);
if (type !== 'function') {
throw new Error(
methods.toString() + " `" + (this.opts.name || path) +"`: `middleware` "
+ "must be a function, not `" + type + "`"
);
}
}, this);
// 根据路由路径生成路由正则表达式
// 将params参数信息保存在paramNames数组中
this.path = path;
this.regexp = pathToRegExp(path, this.paramNames, this.opts);
debug('defined route %s %s', this.methods, this.opts.prefix + this.path);
};

以上构造函数,用来初始化路由路径,路由请求方法数组,路由处理函数数组,路由正则表达式以及params参数信息。

其中path-to-regexp方法根据路径字符串生成正则表达式,可以实现路由的匹配以及params参数的捕获。

  • 验证路由
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
/**
* Returns whether request `path` matches route.
*
* @param {String} path
* @returns {Boolean}
* @private
*/
Layer.prototype.match = function (path) {
return this.regexp.test(path);
};
/**
* Returns map of URL parameters for given `path` and `paramNames`.
* 根据paramNames中的参数信息以及captrues方法,可以获取到当前路由params参数的键值对:
*
* @param {String} path
* @param {Array.<String>} captures
* @param {Object=} existingParams
* @returns {Object}
* @private
*/
Layer.prototype.params = function (path, captures, existingParams) {
var params = existingParams || {};
for (var len = captures.length, i=0; i<len; i++) {
if (this.paramNames[i]) {
var c = captures[i];
params[this.paramNames[i].name] = c ? safeDecodeURIComponent(c) : c;
}
}
return params;
};
/**
* Returns array of regexp url path captures.
*
* @param {String} path
* @returns {Array.<String>}
* @private
*/
Layer.prototype.captures = function (path) {
if (this.opts.ignoreCaptures) return [];
return path.match(this.regexp).slice(1);
};
  • safeDecodeURIComponent

decodeURIComponent只能转义encodeURIComponent编码过的方法,如果编码不符合要求,decodeURIComponent则会抛出URIError,所以koa-router中做了安全处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Safe decodeURIComponent, won't throw any error.
* If `decodeURIComponent` error happen, just return the original value.
*
* @param {String} text
* @returns {String} URL decode original string.
* @private
*/
function safeDecodeURIComponent(text) {
try {
return decodeURIComponent(text);
} catch (e) {
return text;
}
}
  • param
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
/**
* Run validations on route named parameters.
*
* @example
*
* router
* .param('user', function (id, ctx, next) {
* ctx.user = users[id];
* if (!user) return ctx.status = 404;
* next();
* })
* .get('/users/:user', function (ctx, next) {
* ctx.body = ctx.user;
* });
*
* @param {String} param
* @param {Function} middleware
* @returns {Layer}
* @private
*/
Layer.prototype.param = function (param, fn) {
var stack = this.stack;
var params = this.paramNames;
var middleware = function (ctx, next) {
return fn.call(this, ctx.params[param], ctx, next);
};
middleware.param = param;
var names = params.map(function (p) {
return p.name;
});
var x = names.indexOf(param);
if (x > -1) {
// iterate through the stack, to figure out where to place the handler fn
stack.some(function (fn, i) {
// param handlers are always first, so when we find an fn w/o a param property, stop here
// if the param handler at this part of the stack comes after the one we are adding, stop here
if (!fn.param || names.indexOf(fn.param) > x) {
// inject this param handler right before the current item
stack.splice(i, 0, middleware);
return true; // then break the loop
}
});
}
return this;
};
  • 设置路由路径的前缀
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Prefix route path.
*
* @param {String} prefix
* @returns {Layer}
* @private
*/
Layer.prototype.setPrefix = function (prefix) {
if (this.path) {
this.path = prefix + this.path;
this.paramNames = [];
this.regexp = pathToRegExp(this.path, this.paramNames, this.opts);
}
return this;
};
  • URL生成
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
/**
* Generate URL for route using given `params`.
*
* @example
*
* var route = new Layer(['GET'], '/users/:id', fn);
*
* route.url({ id: 123 }); // => "/users/123"
*
* @param {Object} params url parameters
* @returns {String}
* @private
*/
Layer.prototype.url = function (params, options) {
var args = params;
var url = this.path.replace(/\(\.\*\)/g, '');
var toPath = pathToRegExp.compile(url);
var replaced;
if (typeof params != 'object') {
args = Array.prototype.slice.call(arguments);
if (typeof args[args.length - 1] == 'object') {
options = args[args.length - 1];
args = args.slice(0, args.length - 1);
}
}
var tokens = pathToRegExp.parse(url);
var replace = {};
if (args instanceof Array) {
for (var len = tokens.length, i=0, j=0; i<len; i++) {
if (tokens[i].name) replace[tokens[i].name] = args[j++];
}
} else if (tokens.some(token => token.name)) {
replace = params;
} else {
options = params;
}
replaced = toPath(replace);
if (options && options.query) {
var replaced = new uri(replaced)
replaced.search(options.query);
return replaced.toString();
}
return replaced;
};