资讯专栏INFORMATION COLUMN

koa-router源码学习

qpwoeiru96 / 2956人阅读

摘要:源码架构图调用链路请求调用流程存放方法指定的参数的中间件存放实例存放路径参数的一些属性,存放该路由的中间件如果支持请求,一并支持请求将路由转为正则表达式给实例挂载方法如果指定了路由属性路由注册实例数组,初始为空数

源码架构图

调用链路-routes()

HTTP请求调用流程

Usage

</>复制代码

  1. const Koa = require("koa");
  2. const Router = require("koa-router");
  3. const app = new Koa();
  4. const router = new Router();
  5. router.get("/", async (ctx, next) => {
  6. console.log("index");
  7. ctx.body = "index";
  8. });
  9. app.use(router.routes()).use(router.allowedMethods());
  10. app.listen(3000);
Router

</>复制代码

  1. function Router(opts) {
  2. if (!(this instanceof Router)) {
  3. return new Router(opts);
  4. }
  5. this.opts = opts || {};
  6. this.methods = this.opts.methods || [
  7. "HEAD",
  8. "OPTIONS",
  9. "GET",
  10. "PUT",
  11. "PATCH",
  12. "POST",
  13. "DELETE"
  14. ];
  15. // 存放router.param方法指定的参数的中间件
  16. this.params = {};
  17. // 存放layer实例
  18. this.stack = [];
  19. };
Layer

</>复制代码

  1. function Layer(path, methods, middleware, opts) {
  2. this.opts = opts || {};
  3. this.name = this.opts.name || null;
  4. this.methods = [];
  5. // 存放path路径参数的一些属性,eg: /test/:str => { name: str, prefix: "/" ....}
  6. this.paramNames = [];
  7. // 存放该路由的中间件
  8. this.stack = Array.isArray(middleware) ? middleware : [middleware];
  9. methods.forEach(function(method) {
  10. var l = this.methods.push(method.toUpperCase());
  11. // 如果支持get请求,一并支持head请求
  12. if (this.methods[l-1] === "GET") {
  13. this.methods.unshift("HEAD");
  14. }
  15. }, this);
  16. // ensure middleware is a function
  17. this.stack.forEach(function(fn) {
  18. var type = (typeof fn);
  19. if (type !== "function") {
  20. throw new Error(
  21. methods.toString() + " `" + (this.opts.name || path) +"`: `middleware` "
  22. + "must be a function, not `" + type + "`"
  23. );
  24. }
  25. }, this);
  26. this.path = path;
  27. // 将路由转为正则表达式
  28. this.regexp = pathToRegExp(path, this.paramNames, this.opts);
  29. debug("defined route %s %s", this.methods, this.opts.prefix + this.path);
  30. };
给Router实例挂载HTTP方法

</>复制代码

  1. /**
  2. * Create `router.verb()` methods, where *verb* is one of the HTTP verbs such
  3. * as `router.get()` or `router.post()`.
  4. *
  5. * Match URL patterns to callback functions or controller actions using `router.verb()`,
  6. * where **verb** is one of the HTTP verbs such as `router.get()` or `router.post()`.
  7. *
  8. * Additionaly, `router.all()` can be used to match against all methods.
  9. *
  10. * ```javascript
  11. * router
  12. * .get("/", (ctx, next) => {
  13. * ctx.body = "Hello World!";
  14. * })
  15. * .post("/users", (ctx, next) => {
  16. * // ...
  17. * })
  18. * .put("/users/:id", (ctx, next) => {
  19. * // ...
  20. * })
  21. * .del("/users/:id", (ctx, next) => {
  22. * // ...
  23. * })
  24. * .all("/users/:id", (ctx, next) => {
  25. * // ...
  26. * });
  27. * ```
  28. *
  29. * When a route is matched, its path is available at `ctx._matchedRoute` and if named,
  30. * the name is available at `ctx._matchedRouteName`
  31. *
  32. * Route paths will be translated to regular expressions using
  33. * [path-to-regexp](https://github.com/pillarjs/path-to-regexp).
  34. *
  35. * Query strings will not be considered when matching requests.
  36. *
  37. * #### Named routes
  38. *
  39. * Routes can optionally have names. This allows generation of URLs and easy
  40. * renaming of URLs during development.
  41. *
  42. * ```javascript
  43. * router.get("user", "/users/:id", (ctx, next) => {
  44. * // ...
  45. * });
  46. *
  47. * router.url("user", 3);
  48. * // => "/users/3"
  49. * ```
  50. *
  51. * #### Multiple middleware
  52. *
  53. * Multiple middleware may be given:
  54. *
  55. * ```javascript
  56. * router.get(
  57. * "/users/:id",
  58. * (ctx, next) => {
  59. * return User.findOne(ctx.params.id).then(function(user) {
  60. * ctx.user = user;
  61. * next();
  62. * });
  63. * },
  64. * ctx => {
  65. * console.log(ctx.user);
  66. * // => { id: 17, name: "Alex" }
  67. * }
  68. * );
  69. * ```
  70. *
  71. * ### Nested routers
  72. *
  73. * Nesting routers is supported:
  74. *
  75. * ```javascript
  76. * var forums = new Router();
  77. * var posts = new Router();
  78. *
  79. * posts.get("/", (ctx, next) => {...});
  80. * posts.get("/:pid", (ctx, next) => {...});
  81. * forums.use("/forums/:fid/posts", posts.routes(), posts.allowedMethods());
  82. *
  83. * // responds to "/forums/123/posts" and "/forums/123/posts/123"
  84. * app.use(forums.routes());
  85. * ```
  86. *
  87. * #### Router prefixes
  88. *
  89. * Route paths can be prefixed at the router level:
  90. *
  91. * ```javascript
  92. * var router = new Router({
  93. * prefix: "/users"
  94. * });
  95. *
  96. * router.get("/", ...); // responds to "/users"
  97. * router.get("/:id", ...); // responds to "/users/:id"
  98. * ```
  99. *
  100. * #### URL parameters
  101. *
  102. * Named route parameters are captured and added to `ctx.params`.
  103. *
  104. * ```javascript
  105. * router.get("/:category/:title", (ctx, next) => {
  106. * console.log(ctx.params);
  107. * // => { category: "programming", title: "how-to-node" }
  108. * });
  109. * ```
  110. *
  111. * The [path-to-regexp](https://github.com/pillarjs/path-to-regexp) module is
  112. * used to convert paths to regular expressions.
  113. *
  114. * @name get|put|post|patch|delete|del
  115. * @memberof module:koa-router.prototype
  116. * @param {String} path
  117. * @param {Function=} middleware route middleware(s)
  118. * @param {Function} callback route callback
  119. * @returns {Router}
  120. */
  121. var methods = require("methods");
  122. methods.forEach(function (method) {
  123. Router.prototype[method] = function (name, path, middleware) {
  124. var middleware;
  125. // 如果指定了路由name属性
  126. if (typeof path === "string" || path instanceof RegExp) {
  127. middleware = Array.prototype.slice.call(arguments, 2);
  128. } else {
  129. middleware = Array.prototype.slice.call(arguments, 1);
  130. path = name;
  131. name = null;
  132. }
  133. // 路由注册
  134. this.register(path, [method], middleware, {
  135. name: name
  136. });
  137. return this;
  138. };
  139. });
Router.prototype.register

</>复制代码

  1. /**
  2. * Create and register a route.
  3. *
  4. * @param {String} path Path string.
  5. * @param {Array.} methods Array of HTTP verbs.
  6. * @param {Function} middleware Multiple middleware also accepted.
  7. * @returns {Layer}
  8. * @private
  9. */
  10. Router.prototype.register = function (path, methods, middleware, opts) {
  11. opts = opts || {};
  12. var router = this;
  13. // layer实例数组,初始为空数组
  14. var stack = this.stack;
  15. // support array of paths
  16. if (Array.isArray(path)) {
  17. // 如果是多路径,递归注册路由
  18. path.forEach(function (p) {
  19. router.register.call(router, p, methods, middleware, opts);
  20. });
  21. return this;
  22. }
  23. // create route
  24. var route = new Layer(path, methods, middleware, {
  25. end: opts.end === false ? opts.end : true,
  26. name: opts.name,
  27. sensitive: opts.sensitive || this.opts.sensitive || false,
  28. strict: opts.strict || this.opts.strict || false,
  29. prefix: opts.prefix || this.opts.prefix || "",
  30. ignoreCaptures: opts.ignoreCaptures
  31. });
  32. // 设置前置路由
  33. if (this.opts.prefix) {
  34. route.setPrefix(this.opts.prefix);
  35. }
  36. // add parameter middleware
  37. Object.keys(this.params).forEach(function (param) {
  38. // 将router中this.params维护的参数中间件挂载到layer实例中
  39. route.param(param, this.params[param]);
  40. }, this);
  41. // 所有layer实例存放在router的stack属性中
  42. stack.push(route);
  43. return route;
  44. };
Router.prototype.match

</>复制代码

  1. /**
  2. * Match given `path` and return corresponding routes.
  3. *
  4. * @param {String} path
  5. * @param {String} method
  6. * @returns {Object.} returns layers that matched path and
  7. * path and method.
  8. * @private
  9. */
  10. Router.prototype.match = function (path, method) {
  11. // layer实例组成的数组
  12. var layers = this.stack;
  13. var layer;
  14. var matched = {
  15. path: [],
  16. pathAndMethod: [],
  17. route: false
  18. };
  19. for (var len = layers.length, i = 0; i < len; i++) {
  20. layer = layers[i];
  21. debug("test %s %s", layer.path, layer.regexp);
  22. // 1.匹配路由
  23. if (layer.match(path)) {
  24. matched.path.push(layer);
  25. // 2.匹配http请求方法
  26. if (layer.methods.length === 0 || ~layer.methods.indexOf(method)) {
  27. matched.pathAndMethod.push(layer);
  28. // 3.指定了http请求方法,判定为路由匹配成功
  29. if (layer.methods.length) matched.route = true;
  30. }
  31. }
  32. }
  33. return matched;
  34. };
Router.prototype.routes

</>复制代码

  1. /**
  2. * Returns router middleware which dispatches a route matching the request.
  3. *
  4. * @returns {Function}
  5. */
  6. Router.prototype.routes = Router.prototype.middleware = function () {
  7. var router = this;
  8. var dispatch = function dispatch(ctx, next) {
  9. debug("%s %s", ctx.method, ctx.path);
  10. // 请求路由
  11. var path = router.opts.routerPath || ctx.routerPath || ctx.path;
  12. // 将注册路由和请求的路由进行匹配
  13. var matched = router.match(path, ctx.method);
  14. var layerChain, layer, i;
  15. if (ctx.matched) {
  16. ctx.matched.push.apply(ctx.matched, matched.path);
  17. } else {
  18. ctx.matched = matched.path;
  19. }
  20. ctx.router = router;
  21. // route属性是三次匹配的结果,表示最终是否匹配成功
  22. if (!matched.route) return next();
  23. // 同时满足路由匹配和http请求方法的layer数组
  24. var matchedLayers = matched.pathAndMethod
  25. // 匹配多个路由时认为最后一个是匹配有效的路由
  26. var mostSpecificLayer = matchedLayers[matchedLayers.length - 1]
  27. ctx._matchedRoute = mostSpecificLayer.path;
  28. if (mostSpecificLayer.name) {
  29. ctx._matchedRouteName = mostSpecificLayer.name;
  30. }
  31. // 将匹配的路由reduce为一个数组
  32. layerChain = matchedLayers.reduce(function(memo, layer) {
  33. // 执行注册路由中间件之前,对context中的一些参数进行设置
  34. memo.push(function(ctx, next) {
  35. // :path/XXX 捕获的路径
  36. ctx.captures = layer.captures(path, ctx.captures);
  37. // 捕获的路径上的参数, { key: value }
  38. ctx.params = layer.params(path, ctx.captures, ctx.params);
  39. // 路由名称
  40. ctx.routerName = layer.name;
  41. return next();
  42. });
  43. // 返回路由中间件的数组
  44. return memo.concat(layer.stack);
  45. }, []);
  46. // 处理为promise对象
  47. return compose(layerChain)(ctx, next);
  48. };
  49. dispatch.router = this;
  50. return dispatch;
  51. };
Router.prototype.allowedMethod

</>复制代码

  1. /**
  2. * Returns separate middleware for responding to `OPTIONS` requests with
  3. * an `Allow` header containing the allowed methods, as well as responding
  4. * with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
  5. *
  6. * @example
  7. *
  8. * ```javascript
  9. * var Koa = require("koa");
  10. * var Router = require("koa-router");
  11. *
  12. * var app = new Koa();
  13. * var router = new Router();
  14. *
  15. * app.use(router.routes());
  16. * app.use(router.allowedMethods());
  17. * ```
  18. *
  19. * **Example with [Boom](https://github.com/hapijs/boom)**
  20. *
  21. * ```javascript
  22. * var Koa = require("koa");
  23. * var Router = require("koa-router");
  24. * var Boom = require("boom");
  25. *
  26. * var app = new Koa();
  27. * var router = new Router();
  28. *
  29. * app.use(router.routes());
  30. * app.use(router.allowedMethods({
  31. * throw: true,
  32. * notImplemented: () => new Boom.notImplemented(),
  33. * methodNotAllowed: () => new Boom.methodNotAllowed()
  34. * }));
  35. * ```
  36. *
  37. * @param {Object=} options
  38. * @param {Boolean=} options.throw throw error instead of setting status and header
  39. * @param {Function=} options.notImplemented throw the returned value in place of the default NotImplemented error
  40. * @param {Function=} options.methodNotAllowed throw the returned value in place of the default MethodNotAllowed error
  41. * @returns {Function}
  42. */
  43. Router.prototype.allowedMethods = function (options) {
  44. options = options || {};
  45. var implemented = this.methods;
  46. return function allowedMethods(ctx, next) {
  47. // 所有中间件执行完之后执行allowedMethod方法
  48. return next().then(function() {
  49. var allowed = {};
  50. // 没有响应状态码或者响应了404
  51. if (!ctx.status || ctx.status === 404) {
  52. // 在match方法中,匹配的路由的layer实例对象组成的数组
  53. ctx.matched.forEach(function (route) {
  54. route.methods.forEach(function (method) {
  55. // 把匹配的路由的http方法保存起来,认为是允许的http请求方法
  56. allowed[method] = method;
  57. });
  58. });
  59. var allowedArr = Object.keys(allowed);
  60. // 如果该方法在router实例的methods中不存在
  61. if (!~implemented.indexOf(ctx.method)) {
  62. // 如果在初始化router时配置了throw属性为true
  63. if (options.throw) {
  64. var notImplementedThrowable;
  65. if (typeof options.notImplemented === "function") {
  66. // 指定了报错函数
  67. notImplementedThrowable = options.notImplemented(); // set whatever the user returns from their function
  68. } else {
  69. // 没有指定则抛出http异常
  70. notImplementedThrowable = new HttpError.NotImplemented();
  71. }
  72. throw notImplementedThrowable;
  73. } else {
  74. // 没有配置throw则响应501
  75. ctx.status = 501;
  76. // 设置响应头中的allow字段,返回允许的http方法
  77. ctx.set("Allow", allowedArr.join(", "));
  78. }
  79. } else if (allowedArr.length) {
  80. if (ctx.method === "OPTIONS") {
  81. // 如果是OPTIONS请求,则认为是请求成功,响应200,并根据OPTIONS请求约定返回允许的http方法
  82. ctx.status = 200;
  83. ctx.body = "";
  84. ctx.set("Allow", allowedArr.join(", "));
  85. } else if (!allowed[ctx.method]) {
  86. // 如果请求方法在router实例的methods中存在,但是在匹配的路由中该http方法不存在
  87. if (options.throw) {
  88. var notAllowedThrowable;
  89. if (typeof options.methodNotAllowed === "function") {
  90. notAllowedThrowable = options.methodNotAllowed(); // set whatever the user returns from their function
  91. } else {
  92. notAllowedThrowable = new HttpError.MethodNotAllowed();
  93. }
  94. throw notAllowedThrowable;
  95. } else {
  96. // 响应405 http请求方法错误
  97. ctx.status = 405;
  98. ctx.set("Allow", allowedArr.join(", "));
  99. }
  100. }
  101. }
  102. }
  103. });
  104. };
  105. };
Router.prototype.use

</>复制代码

  1. /**
  2. * Use given middleware.
  3. *
  4. * Middleware run in the order they are defined by `.use()`. They are invoked
  5. * sequentially, requests start at the first middleware and work their way
  6. * "down" the middleware stack.
  7. *
  8. * @example
  9. *
  10. * ```javascript
  11. * // session middleware will run before authorize
  12. * router
  13. * .use(session())
  14. * .use(authorize());
  15. *
  16. * // use middleware only with given path
  17. * router.use("/users", userAuth());
  18. *
  19. * // or with an array of paths
  20. * router.use(["/users", "/admin"], userAuth());
  21. *
  22. * app.use(router.routes());
  23. * ```
  24. *
  25. * @param {String=} path
  26. * @param {Function} middleware
  27. * @param {Function=} ...
  28. * @returns {Router}
  29. */
  30. Router.prototype.use = function () {
  31. var router = this;
  32. var middleware = Array.prototype.slice.call(arguments);
  33. var path;
  34. // support array of paths
  35. // 如果第一个参数是一个数组,且数组中元素为字符串
  36. if (Array.isArray(middleware[0]) && typeof middleware[0][0] === "string") {
  37. // 递归调用use方法
  38. middleware[0].forEach(function (p) {
  39. router.use.apply(router, [p].concat(middleware.slice(1)));
  40. });
  41. return this;
  42. }
  43. var hasPath = typeof middleware[0] === "string";
  44. if (hasPath) {
  45. path = middleware.shift();
  46. }
  47. middleware.forEach(function (m) {
  48. // 如果这个中间件是由router.routes()方法返回的dispatch中间件,即这是一个嵌套的路由
  49. if (m.router) {
  50. // 遍历router.stack属性中所有的layer
  51. m.router.stack.forEach(function (nestedLayer) {
  52. // 被嵌套的路由需要以父路由path为前缀
  53. if (path) nestedLayer.setPrefix(path);
  54. // 如果父路由有指定前缀,被嵌套的路由需要把这个前缀再加上
  55. if (router.opts.prefix) nestedLayer.setPrefix(router.opts.prefix);
  56. router.stack.push(nestedLayer);
  57. });
  58. if (router.params) {
  59. Object.keys(router.params).forEach(function (key) {
  60. m.router.param(key, router.params[key]);
  61. });
  62. }
  63. } else {
  64. router.register(path || "(.*)", [], m, { end: false, ignoreCaptures: !hasPath });
  65. }
  66. });
  67. return this;
  68. };

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/97520.html

相关文章

  • 教你从写一个迷你koa-router到阅读koa-router源码

    摘要:本打算教一步步实现,因为要解释的太多了,所以先简化成版本,从实现部分功能到阅读源码,希望能让你好理解一些。 本打算教一步步实现koa-router,因为要解释的太多了,所以先简化成mini版本,从实现部分功能到阅读源码,希望能让你好理解一些。希望你之前有读过koa源码,没有的话,给你链接 最核心需求-路由匹配 router最重要的就是路由匹配,我们就从最核心的入手 router.get...

    yzzz 评论0 收藏0
  • Koa-router 优先级问题

    摘要:问题描述在使用作为路由遇到了一个优先级问题如下代码在访问时路由会优先匹配到路由返回这个问题就很尴尬了项目空闲下来去翻看源码终于找到了原因问题原因的源码并不长和两个文件加起来共一千多行代码建议可以结合这篇文章阅读其中造成这个问题的原因 问题描述 在使用Koa-router作为路由遇到了一个优先级问题.如下代码 // routerPage.js file const router = re...

    Paul_King 评论0 收藏0
  • koa-router 源码浅析

    摘要:代码结构执行流程上面两张图主要将的整体代码结构和大概的执行流程画了出来,画的不够具体。那下面主要讲中的几处的关键代码解读一下。全局的路由参数处理的中间件组成的对象。 代码结构 showImg(https://segmentfault.com/img/remote/1460000007468236?w=1425&h=1772); 执行流程 showImg(https://segmentf...

    SillyMonkey 评论0 收藏0
  • koa源码阅读[2]-koa-router

    摘要:第三篇,有关生态中比较重要的一个中间件第一篇源码阅读第二篇源码阅读与是什么首先,因为是一个管理中间件的平台,而注册一个中间件使用来执行。这里写入的多个中间件都是针对该生效的。 第三篇,有关koa生态中比较重要的一个中间件:koa-router 第一篇:koa源码阅读-0 第二篇:koa源码阅读-1-koa与koa-compose koa-router是什么 首先,因为koa是一个管...

    oneasp 评论0 收藏0
  • 玩转Koa -- koa-router原理解析

    摘要:四路由注册构造函数首先看了解一下构造函数限制必须采用关键字服务器支持的请求方法,后续方法会用到保存前置处理函数存储在构造函数中初始化的和属性最为重要,前者用来保存前置处理函数,后者用来保存实例化的对象。 一、前言   Koa为了保持自身的简洁,并没有捆绑中间件。但是在实际的开发中,我们需要和形形色色的中间件打交道,本文将要分析的是经常用到的路由中间件 -- koa-router。   ...

    wthee 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<