RoutingSystem.js 970 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const express = require('express');
  2. const path = require('path');
  3. function _fail(req,res) {
  4. res.sendStatus(500);
  5. }
  6. function sendFile(req,res,next, file) {
  7. let p = path.join(__dirname + '/../public' + file);
  8. return res.sendFile(p);
  9. }
  10. function _setupRoutes(routes, router) {
  11. for(let i in routes){
  12. let fn = _fail;
  13. switch(routes[i].type) {
  14. case 'file':
  15. fn = (r,w,n) => sendFile(r,w,n,routes[i].file);
  16. break;
  17. case 'custom':
  18. fn = routes[i].customFn;
  19. break;
  20. }
  21. router[routes[i].method]([routes[i].endpoint], fn);
  22. }
  23. }
  24. class RoutingSystem {
  25. constructor() {
  26. this.currentRoutes = [];
  27. this.router = express.Router();
  28. }
  29. addRoute(route) {
  30. this.currentRoutes.push(route);
  31. }
  32. loadRoutes(routes, router, prefix = '/', middlewares = []) {
  33. if(router === undefined)
  34. router = express.Router();
  35. _setupRoutes(routes, router);
  36. this.router.use(prefix, middlewares, router);
  37. return router;
  38. }
  39. }
  40. module.exports = new RoutingSystem();