|
| 1 | + |
| 2 | +const fs = require('fs'); |
| 3 | + |
| 4 | +// add url-route in /controllers: |
| 5 | + |
| 6 | +function addMapping(router, mapping) { |
| 7 | + for (var url in mapping) { |
| 8 | + if (url.startsWith('GET ')) { |
| 9 | + var path = url.substring(4); |
| 10 | + router.get(path, mapping[url]); |
| 11 | + console.log(`register URL mapping: GET ${path}`); |
| 12 | + } else if (url.startsWith('POST ')) { |
| 13 | + var path = url.substring(5); |
| 14 | + router.post(path, mapping[url]); |
| 15 | + console.log(`register URL mapping: POST ${path}`); |
| 16 | + } else if (url.startsWith('PUT ')) { |
| 17 | + var path = url.substring(4); |
| 18 | + router.put(path, mapping[url]); |
| 19 | + console.log(`register URL mapping: PUT ${path}`); |
| 20 | + } else if (url.startsWith('DELETE ')) { |
| 21 | + var path = url.substring(7); |
| 22 | + router.del(path, mapping[url]); |
| 23 | + console.log(`register URL mapping: DELETE ${path}`); |
| 24 | + } else { |
| 25 | + console.log(`invalid URL: ${url}`); |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +function addControllers(router, dir) { |
| 31 | + var files = fs.readdirSync(__dirname + '/' + dir); |
| 32 | + var js_files = files.filter((f) => { |
| 33 | + return f.endsWith('.js'); |
| 34 | + }, files); |
| 35 | + |
| 36 | + for (var f of js_files) { |
| 37 | + console.log(`process controller: ${f}...`); |
| 38 | + let mapping = require(__dirname + '/' + dir + '/' + f); |
| 39 | + addMapping(router, mapping); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +module.exports = function (dir) { |
| 44 | + let |
| 45 | + controllers_dir = dir || 'controllers', |
| 46 | + router = require('koa-router')(); |
| 47 | + addControllers(router, controllers_dir); |
| 48 | + return router.routes(); |
| 49 | +}; |
0 commit comments