If you gonna validate the whole body and the body is an array of objects, you may do this by creating middleware chain with validator(1), errors check(2) and useful middleware(2).
import { body, validationResult } from "express-validator";
// we will use lodash method like an example
import { isArray } from "lodash";
app.post(
"/users",
// the second argument "meta" contains whole request and body
body().custom((_unused, meta) => myCustomValidator(meta.req.body)), // (1)
ensureNoErrors, // (2)
doUsefulStuff // (3)
);
Actually that's all: you need to use construction (1) for getting result.
In order to clarify methods implementation:
function myCustomValidator(body) {
if (isArray(body)) {
throw new Error("Body must be an array");
}
// do other checks with the whole body, throw error if something is wrong
return true;
}
function ensureNoErrors(req, res, next) {
// check if validation result contains errors and if so return 400
const errors = validationResult(req);
if (errors.isEmpty()) {
return next();
}
return res.status(400).json({
// return message of the first error like an example
error: errors.array()[0].msg,
});
}
function doUsefulStuff(req, res, next) {
// do some useful stuff with payload
const [user1, user2] = req.body;
}
Link to express-validator documentation.