48 lines
1.4 KiB
JavaScript
48 lines
1.4 KiB
JavaScript
const fs = require("fs")
|
|
const os = require('os');
|
|
|
|
function addMapping(router, mapping) {
|
|
for (var url in mapping) {
|
|
if (url.startsWith('GET ')) {
|
|
var path = url.substring(4);
|
|
router.get(path, mapping[url]);
|
|
console.log(`register URL mapping: GET ${path}`);
|
|
} else if (url.startsWith('POST ')) {
|
|
var path = url.substring(5);
|
|
router.post(path, mapping[url]);
|
|
console.log(`register URL mapping: POST ${path}`);
|
|
} else {
|
|
console.log(`invalid URL: ${url}`);
|
|
}
|
|
}
|
|
}
|
|
|
|
function addControllers(router, controllers_dir) {
|
|
let ostype = os.type() == "Windows_NT"
|
|
let dir;
|
|
if (ostype) {
|
|
dir = __dirname.replace("\\bin", "")
|
|
} else {
|
|
dir = __dirname.replace("/bin", "")
|
|
}
|
|
|
|
var files = fs.readdirSync(dir + "/" + controllers_dir);
|
|
var js_files = files.filter((f) => {
|
|
return f.endsWith('.js');
|
|
});
|
|
|
|
for (var f of js_files) {
|
|
console.log(`process controller: ${f}...`);
|
|
let mapping = require(dir + `/${controllers_dir}/` + f);
|
|
addMapping(router, mapping);
|
|
}
|
|
}
|
|
module.exports = function (dir) {
|
|
let
|
|
controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
|
|
router = require('koa-router')();
|
|
addControllers(router, controllers_dir);
|
|
return router.routes();
|
|
// return 1;
|
|
};
|