Ade Firman Fauzi
Ade Firman Fauzi

Reputation: 377

Routes in express JS taken from DB

I want to use routes something like this.

For example :

routes.use((req, res, next) => {
  /**
   * I have an example routes from database and i was passing into variable
   * I'm assign fromDb as 'api/test'
   */
  var a = fromDb;
  next()
})

routes.get(a, (req, res, next) => {
  console.log(req.path)
})

I know, a variable in next routes do not get a value from DB cause functional scope. So, any idea for solve this method. I just wondering if I can using modular like this

const DBRoutes = require('lib/example.js')

router.get(DBRoutes, (req, res) => {
  console.log(req.path)
})

Any idea for the best method? Thanks

Upvotes: 1

Views: 361

Answers (2)

Neeraj Sharma
Neeraj Sharma

Reputation: 1105

routes.use((req, res, next) => {
  /**
   * I have an example routes from database and i was passing into variable
   * I'm assign fromDb as 'api/test'
   */
  res.locals.fromDb = fromDb;
  next()
})

routes.get('/your/route', (req, res, next) => {
  console.log(req.path);
  console.log(res.locals.fromDb);
});

This is one way of passing variables through different middlewares in express.

I don't think you can dynamically set up routes for express web server. However, routes are set up once during startup. You can get the routes from database at that time.

const route = await routeFromDatabase();

routes.get(route, (req, res, next) => {
  console.log(req.path);
  console.log(res.locals.fromDb);
});

If you change the database after startup, you will have to restart the node app.

Update 19th Feb 2018: User mentioned the use case as API Gateway. This is worth exploring for such use cases: https://www.express-gateway.io/

Upvotes: 1

Chris Phillips
Chris Phillips

Reputation: 673

You want to add a route based on content in your database

So you could do the lookup and on success create the route

eg:

dbConnection.lookup(...some query)
   .then((pathFromDB) => {
     // where pathfromDb = /api/test
     routes.get(pathFromDB, (req, res, next) => {
       console.log(req.path)
     })
   }); 

Upvotes: 1

Related Questions