container.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import * as controllers from './controllers/'
  2. import * as middlewares from './middleware/'
  3. import { routes } from './routes'
  4. import express from 'express'
  5. interface ControllerCollection {
  6. [key: string]: any
  7. }
  8. const controllerInstances: ControllerCollection = {}
  9. const router = express.Router()
  10. export function loadRoute(): express.Router {
  11. for (const route of routes) {
  12. const [controllerName, controllerAction] = route.action.split('@')
  13. const middlewareList = []
  14. if (!isControllerInitialized(controllerName)) {
  15. if (isControllerExisted(controllerName)) {
  16. controllerInstances[controllerName] = new controllers[controllerName]()
  17. } else {
  18. throw new Error(`Controller ${controllerName} not exist.`)
  19. }
  20. }
  21. if (route.middlewares) {
  22. for (const middleware of route.middlewares) {
  23. if (!isMiddlewareExists(middleware)) {
  24. throw new Error(`Middleware ${middleware} not exist.`)
  25. }
  26. middlewareList.push(middlewares[middleware])
  27. }
  28. }
  29. switch (route.method) {
  30. case 'get':
  31. router.get(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
  32. break
  33. case 'post':
  34. router.post(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
  35. break
  36. case 'delete':
  37. router.delete(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
  38. break
  39. case 'patch':
  40. router.patch(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
  41. break
  42. case 'put':
  43. router.put(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
  44. break
  45. }
  46. }
  47. return router
  48. }
  49. function isControllerInitialized(controller: string): boolean {
  50. return controller in controllerInstances
  51. }
  52. function isControllerExisted(controller: string): controller is keyof typeof controllers {
  53. return controller in controllers
  54. }
  55. function isActionExisted(controller: object, action: string) {
  56. return action in controller
  57. }
  58. function isMiddlewareExists(middlewareName: string): middlewareName is keyof typeof middlewares {
  59. return middlewareName in middlewares
  60. }
  61. function isMethodExisted(method: string): method is keyof typeof router {
  62. const httpMethods = ['get', 'post', 'delete', 'put', 'patch']
  63. if (!httpMethods.includes(method)) {
  64. return false
  65. }
  66. return method in router
  67. }