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:
- Can I refactor the middleware above so that it handles multiple parameters and I don’t have to repeat myself?
- 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 assignsreq.senderId
the validated ID, etc.)
Thank you!!