Home > Software design >  Use prefix for route routes in express
Use prefix for route routes in express

Time:10-16

How can I do to define a prefix in the index or at least just one per module?

Currently I have this:

Role Module

export class RoleRoutes extends RouteConfig {
  

  constructor(app: Application) {
    super(app, "/role");
  }

  configureRoutes() {
    this.app.route(process.env.PREFIX   this.getName()   '/:id').get([JWT.authenticateJWT, RoleController.getOne.bind(RoleController)]);
    this.app.route(process.env.PREFIX   this.getName()).get([JWT.authenticateJWT, RoleController.getAll.bind(RoleController)]);
    this.app.route(process.env.PREFIX   this.getName()).post([JWT.authenticateJWT, RoleController.create.bind(RoleController)]);
    this.app.route(process.env.PREFIX   this.getName()).put([JWT.authenticateJWT, RoleController.update.bind(RoleController)]);
    return this.app;
  }
}

Index

const routes: Array<RouteConfig> = [];
routes.push(new RoleRoutes(app));

I saw different solutions but they don't match with the structure I have.

CodePudding user response:

Use routers. At the top add

const express = require('express')

(Or however you import stuff) And then in your definition

configureRoutes() {
  var router = express.Router();
  router.use(JWT.authenticateJWT);

  router.get('/:id', RoleController.getOne.bind(RoleController))
  router.get('/', RoleController.getAll.bind(RoleController));
  router.post('/', RoleController.create.bind(RoleController));
  router.put('/', RoleController.update.bind(RoleController));

  this.app.use(process.env.PREFIX   this.getName(), router)
  return this.app;
}
  • Related