| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- import * as controllers from './controllers/'
- import * as middlewares from './middleware/'
- import { routes } from './routes'
- import express from 'express'
- interface ControllerCollection {
- [key: string]: any
- }
- const controllerInstances: ControllerCollection = {}
- const router = express.Router()
- export function loadRoute(): express.Router {
- for (const route of routes) {
- const [controllerName, controllerAction] = route.action.split('@')
- const middlewareList = []
- if (!isControllerInitialized(controllerName)) {
- if (isControllerExisted(controllerName)) {
- controllerInstances[controllerName] = new controllers[controllerName]()
- } else {
- throw new Error(`Controller ${controllerName} not exist.`)
- }
- }
- if (route.middlewares) {
- for (const middleware of route.middlewares) {
- if (!isMiddlewareExists(middleware)) {
- throw new Error(`Middleware ${middleware} not exist.`)
- }
- middlewareList.push(middlewares[middleware])
- }
- }
- switch (route.method) {
- case 'get':
- router.get(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
- break
- case 'post':
- router.post(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
- break
- case 'delete':
- router.delete(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
- break
- case 'patch':
- router.patch(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
- break
- case 'put':
- router.put(route.url, middlewareList, controllerInstances[controllerName][controllerAction])
- break
- }
- }
- return router
- }
- function isControllerInitialized(controller: string): boolean {
- return controller in controllerInstances
- }
- function isControllerExisted(controller: string): controller is keyof typeof controllers {
- return controller in controllers
- }
- function isActionExisted(controller: object, action: string) {
- return action in controller
- }
- function isMiddlewareExists(middlewareName: string): middlewareName is keyof typeof middlewares {
- return middlewareName in middlewares
- }
- function isMethodExisted(method: string): method is keyof typeof router {
- const httpMethods = ['get', 'post', 'delete', 'put', 'patch']
- if (!httpMethods.includes(method)) {
- return false
- }
- return method in router
- }
|