Reduce code repetition in express API route
There are a few ways you can approach it. There is the app.all()
method:
app.all("/api/*", function(req, res, next) { if (req.params._id) { if (mongoose.Types.ObjectId.isValid(req.params._id)) { return next(); } else { // error handle } } next();});
Personally, I don't like catch-alls. I'd rather be more explicit:
function validateMongooseId (req, res, next) { if ( mongoose.Types.ObjectId.isValid(req.params._id) ) { return next(); } else { // error handle }}function handleGet(req, res, next) {}function handlePost(req, res, next) {}function handlePut(req, res, next) {}app.post("/api/brief", handlePost);app.get("/api/brief/:_id", validateMongooseId, handleGet);app.put("/api/brief/:_id", validateMongooseId, handlePut);
I put the .post()
in there to demonstrate why I don't like the catch-all. It clearly doesn't apply to that endpoint. You may have other middleware functions that apply to it, so I'd rather explicitly have them on the endpoints that use them.