routes.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const c = require('./controllers');
  2. const utils = require('./core/utils');
  3. const multer = require('multer');
  4. function initRoutes(app, connPool, config) {
  5. const misc = new c.MiscController(connPool, config);
  6. const reader = new c.ReaderController(connPool, config);
  7. const worker = new c.WorkerController(connPool, config);
  8. //access
  9. const [aAll, aNormal, aSite, aReader, aOmnireader] = // eslint-disable-line no-unused-vars
  10. [config.mode, 'normal', 'site', 'reader', 'omnireader'];
  11. //multer
  12. const storage = multer.diskStorage({
  13. destination: (req, file, cb) => {
  14. cb(null, config.uploadDir);
  15. },
  16. filename: (req, file, cb) => {
  17. cb(null, utils.randomHexString(30));
  18. }
  19. });
  20. const upload = multer({ storage, limits: {fileSize: config.maxUploadFileSize} });
  21. //routes
  22. const routes = [
  23. ['POST', '/api/config', misc.getConfig.bind(misc), [aAll], {}],
  24. ['POST', '/api/reader/load-book', reader.loadBook.bind(reader), [aAll], {}],
  25. ['POST', '/api/reader/upload-file', [upload.single('file'), reader.uploadFile.bind(reader)], [aAll], {}],
  26. ['POST', '/api/worker/get-state', worker.getState.bind(worker), [aAll], {}],
  27. ];
  28. //to app
  29. for (let route of routes) {
  30. let callbacks = [];
  31. let [httpMethod, path, controllers, access, options] = route;
  32. let controller = controllers;
  33. if (Array.isArray(controllers)) {
  34. controller = controllers[controllers.length - 1];
  35. callbacks = controllers.slice(0, -1);
  36. }
  37. access = new Set(access);
  38. let callback = () => {};
  39. if (access.has(config.mode)) {//allowed
  40. callback = async function(req, res) {
  41. try {
  42. const result = await controller(req, res, options);
  43. if (result !== false)
  44. res.send(result);
  45. } catch (e) {
  46. res.status(500).send({error: e.message});
  47. }
  48. };
  49. } else {//forbidden
  50. callback = async function(req, res) {
  51. res.status(403);
  52. };
  53. }
  54. callbacks.push(callback);
  55. switch (httpMethod) {
  56. case 'GET' :
  57. app.get(path, ...callbacks);
  58. break;
  59. case 'POST':
  60. app.post(path, ...callbacks);
  61. break;
  62. default:
  63. throw new Error(`initRoutes error: unknown httpMethod: ${httpMethod}`);
  64. }
  65. }
  66. }
  67. module.exports = {
  68. initRoutes
  69. }