Handling multiple parameters in app.param()

Hi!

I’m working on the portfolio project (Personal Budget I) and I’m trying to implement app.param() function that handles the id parameter in a GET request:

app.param('id', (req, res, next, id) => {
    const envelopeIndex = Number(id);
    const envelopeId = envelopes.findIndex(envelope => envelope.id === envelopeIndex);
    if (envelopeId === -1) {
        res.status(400).send("Error: No envelope found with this ID");
    }
    req.id = envelopeId;
    next();
});

For another POST request handler that transfers amount from one envelope to another (through their IDs), I also want to validate two route parameters that are both IDs (/envelopes/:from/:to/).

My questions:

  1. Can I refactor the middleware above so that it handles multiple parameters and I don’t have to repeat myself?
  2. If so, is there a way I can dynamically assign to the request object the validated ID (e.g. if I am validating ID of 'from', it assigns req.senderId the validated ID, etc.)

Thank you!!

envelopes.findIndex(envelope => envelope.id === envelopeIndex);

consider using some sort of hashmap/dictionary for the id lookup, linear searches are very slow and the whole point of an id is to have some sort of either constant time or logarithmic lookup time (important when there are many ids).

  • Can I refactor the middleware above so that it handles multiple parameters and I don’t have to repeat myself?

Is the goal to just validate a bunch of ids? Then yes. Then you don’t even need the case of it taking a single id, instead it should take an array of ids and apply the validation logic (hashmaps will make this quicker than findIndex).

  • If so, is there a way I can dynamically assign to the request object the validated ID (e.g. if I am validating ID of ‘from’, it assigns req.senderId the validated ID, etc.)

Very probable, maybe you need to explain the structure and use-case a bit more.

1 Like