blog-server/bin/router.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

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