-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.js
39 lines (36 loc) · 1.18 KB
/
controller.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
const fs = require('fs');
function addMapping(router, mapping) {
for (let url in mapping) {
if (url.startsWith('GET ')) {
let path = url.substring(4);
router.get(path, mapping[url]);
} else if (url.startsWith('POST ')) {
let path = url.substring(5);
router.post(path, mapping[url]);
} else if (url.startsWith('PUT ')) {
var path = url.substring(4);
router.put(path, mapping[url]);
} else if (url.startsWith('DELETE ')) {
var path = url.substring(7);
router.del(path, mapping[url]);
} else {
console.log('invalid URL:'+url);
}
}
}
function addControllers(router, dir) {
let files = fs.readdirSync(__dirname + '/' + dir);
let files_js = files.filter((f) => {
return f.endsWith('.js');
});
for (let f of files_js) {
let mapping = require(__dirname + '/' + dir + '/' + f);
addMapping(router, mapping);
}
}
module.exports = function (dir) {
let controllers_dir = dir || 'controllers';
let router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
};