I have an expresss router, and I'm configuring some routes for it, I pass a validator for the data and a handler, but the validator has to work with some promises so I need to place an await, the code that I wrote looks like this:
constructor() {
this.router = express.Router();
this.router.use(express.json());
this.router.use(express.text({ type: ['text/plain', 'text/html'] }));
}
async addCreateTaskRoute(validator, handler) {
if (!handler) {
throw Error('cannot add empty handler');
}
this.router.post('/tasks', await validator, handler);
return this;
}
Does this solution look alright to you? Are there any other options? The project that this is included in is a middleware, and the validator and handlers come from other modules and the type of them is express RequestHandler
Your validator should call next() asynchronously after successful validation, this will then invoke the next middleware, which is handler. After unsuccessful validation, an error is returned and next() is not called so that no further middlewares are processed.
async function validator(req, res, next) {
var valid = await validationResult(...);
if (valid) next();
else res.status(400).end("Error message");
}
this.router.post("/tasks", validator, handler);