当前位置 : 主页 > 网络编程 > PHP >

wemall开源版微商城代码片段--koa自动加载路由 不区分http请求方法

来源:互联网 收集:自由互联 发布时间:2021-06-30
koa自动加载路由不区分http请求方法 1. [代码] [PHP]代码 作者官网: http://www.wemallshop.com 2. [代码] README.md var app = require('koa')();var koaResourceRouter = require('koa-resource-router');app.use(koaResourceRouter
koa自动加载路由 不区分http请求方法

1. [代码][PHP]代码    

作者官网: http://www.wemallshop.com

2. [代码]README.md    

var app = require('koa')();
var koaResourceRouter = require('koa-resource-router');
app.use(koaResourceRouter(app, {
    root: './app/controller',
    suffix: '.js',
    action: 'index'
}));

exports.index = function*(ctx, next){
    console.log(ctx);
    console.log(ctx.query);
    console.log(ctx.params);
}

3. [代码]index.js    

var path = require('path');
var fs = require('fs');

module.exports = function (app, options) {
    if (!options || typeof options.root === 'string') {
        if (!path.isAbsolute(options.root)) {
            options.root = path.join(process.cwd(), options.root);
        }
    } else {
        throw Error('root must be specified');
    }
    options.suffix = options.suffix || '.js';
    options.action = options.action || 'index';

    return function* koaResource(next) {
        var url = this.url.split('?');
        var querystring = url[1];

        var url = url[0].split(path.sep);
        for (var i = 0; i < url.length; i++) {
            if (i == url.length - 2) {
                url[i] += options.suffix;
            }
        }

        var _url = '';
        var params = [];
        var action = options.action;
        for (var i = 0; i < url.length - 1; i++) {
            if (!url[i]) {
                continue;
            }

            var exists = fs.existsSync(options.root + _url + '/' + url[i]);
            if (exists) {
                _url += '/' + url[i];
            } else {
                params.push(url[i]);
            }

            if (url.length - 2 == i && !exists) {
                throw Error('Not Found');
            }
        }

        this.params = params;
        this.querystring = querystring;

        var _require = require(path.join(options.root, _url));
        yield _require[action](this, next);

        yield next;
    };
};

4. [代码]package.json    

{
  "name": "koa-http-router",
  "version": "1.0.1",
  "description": "koa http router",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/einsqing/koa-http-router.git"
  },
  "keywords": [
    "koa",
    "koa-router",
    "koa-http-router",
    "router"
  ],
  "author": "www.wemallshop.com",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/einsqing/koa-http-router/issues"
  },
  "homepage": "https://github.com/einsqing/koa-http-router#readme",
  "dependencies": {
  }
}
网友评论