[Fixed] Dynamically changing routes in Express

Issue

I have an express server. This is my index.js

let some_parameter = some_value;
const configuredHandler = new Handler(some_parameter);

const server = express();

server
    .get("*", configuredHandler.handleRequest)
    .post("*", configuredHandler.handleRequest)
    .put("*", configuredHandler.handleRequest)
    .delete("*", configuredHandler.handleRequest);

I am trying to update the routes if some_parameter to the Handler changes. So it should create a new instance of configuredHandler and the routes should automatically pick the new handler.
Ideally I want to be able to change some_parameter anywhere else in the code.
I am not sure how to structure it for this.
Please help.

Solution

What you could do is use something similar to a factory. That factory would create a new middleware every time some_parameter changes and save that middleware for future reference.

Whenever one of your routes is called, express would then refer to the current handler in your factory.

I wrote a simple example:

const express = require('express');

class HandlerFactory {

  static currentHandler = (req, res) => res.send('Hello');

  static setValue(value) {
    this.currentHandler = (req, res) => res.send(value);
  }

}

const app = express();
app.post('/change-value', (req, res) => {
  HandlerFactory.setValue(req.query.value);
  res.send();
});
app.use('/handler', (req, res) => HandlerFactory.currentHandler(req, res));

app.listen(3000);

Just run the app, then test its functionality:

$ curl http://localhost:3000/handler
Hello
$ curl -X POST http://localhost:3000/change-value?value=SecondMessage
$ curl http://localhost:3000/handler
SecondMessage

Leave a Reply

(*) Required, Your email will not be published