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

 wemall开源版微商城代码片段--koa路由自动加载模块

来源:互联网 收集:自由互联 发布时间:2021-06-30
1. [代码] [PHP]代码 作者官网: http://www.wemallshop.com 2. [代码] README.md koa自动加载路由Installation$ npm install koa-autoload-routerUse with koavar app = require('koa')();var koaAutoloadRouter = require('koa-autoload-rou

1. [代码][PHP]代码    

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

2. [代码]README.md    

koa自动加载路由

Installation

$ npm install koa-autoload-router
Use with koa

var app = require('koa')();
var koaAutoloadRouter = require('koa-autoload-router');
app.use(koaAutoloadRouter(app, {
    root: './app/controller',
    suffix: '.js',
    prefix: '/v1'
}));

3. [代码]index.js    

var path = require('path');
var fs = require('fs');
var router = require('koa-router')();

function walk(dir) {
    dir = path.resolve(__dirname, dir);
    var files = fs.readdirSync(dir);
    var list = [];
    for (var file of files) {
        if (fs.statSync(dir + '/' + file).isDirectory()) {
            list = list.concat(walk(dir + '/' + file));
        } else {
            list.push(dir + '/' + file);
        }
    }
    return list;
}

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';
    options.prefix = options.prefix || '';

    var paths = walk(options.root);
    paths.forEach(function (value, index) {
        var _path = path.relative(options.root, value);
        _path = _path.slice(0, _path.length - options.suffix.length);

        router.use(options.prefix + '/' + _path, require(value).routes());
    });

    app.use(router.routes());

    return function* koaResource(next) {
        yield* next;
    };
};

4. [代码]package.json    

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