koa中间件之smart-middleware

"自动匹配路由中间件"

Posted by Mzx on November 17, 2016

smart-middleware

smart-middleware 是 koa下的一个用于自动加载路由,并自动根据配置好的规则批准路由对应中间件的中间件。

项目地址

npm
github

安装

npm install smart-middleware

使用

/*step 1 app.js*/
var sm = require('smart-middleware');
var router = require('koa-router')();
var app = require('koa-router')();

var middlewares = [
  {url: '/list',
    fn: [function *(next){
      "use strict";
      this.body = '_m_1';
      yield next;
      this.body += '_end_1';
    }, function *(next){
      "use strict";
      this.body += '_m_2';
      yield next;
      this.body += "_end_2";
    }
    ]},
  {url: '\\^(?!/open)', fn: [function *(next){
    "use strict";
    this.body += '_m_3';
    yield next;
    this.body += '_end_3';
  }, function *(next){
    "use strict";
    this.body += '_m_4';
    yield next;
    this.body += '_end_4';
  }]}
  ,{url: '\\^(/open)', fn: [function *(next){
    this.body = '_m_1';
    yield next;
    this.body += '_end_1';
  }]}
];
sm.autoLoading({router: router/*required*/, middleware:middlewares, path:__dirname +'/routers'/*required absolute path*/});
app.use(router.routes());


/*step 2 /routers/user.js*/
module.exports = function(router){
  router.get('/list', function *(next){
    this.body += '/list';
  });
  router.get('/open/user', function *(next){
    this.body += '/open/user';
  });
};
  • 当访问 /list时, 返回的结果为: ‘_m_1_m_2_m_3_m_4/list_end_4_end_3_end_2_end_1’
  • 当访问 /open/user时,返回的结果为: _m_1/open/user_end_1

注:

  1. smart-middleware只有一个方法autoLoading(router, middleware, path) 。其中routerkoa-router必须传入,path是项目的路由文件夹的绝对路径,也是必须传入。middleware 是管理项目中间件的数组。默认为[]
  2. 参数middleware的格式:

      template: {url: 'url', fn: [m1,m2]}
    
  3. 路由匹配规则:

     url: (url.indexOf('\') === 0)? 'this is regexp' : 'this is common String
    
    • 如果template.url的头部为‘\\’,则需要使用正则匹配,否则使用‘===’匹配
  4. middleware匹配规则
    • 加载中间件时根据url从前往后匹配,形成一个匹配成功的数组,如:
     [{url:'/list', fn:[m_1, m_2]}, {url:'\\^(?!/open)', fn: [m_3, m_4]}]
    

    ,则当访问路由/list时, 匹配上的中间件的执行顺序为: m_1, m_2, m_3, m_4

测试

npm test

反馈