how to reuse single post request express validator for a collection?

Viewed 26

I have 2 endpoints in an express application using express-validators:

router.post(
  "/",
  cors(),
  validators.default,
  asyncHandler(helpers.verify),
  asyncHandler(item.create)
);
router.post(
  "/collection",
  cors(),
  validators.createCollection,
  asyncHandler(helpers.verify),
  asyncHandler(item.createCollection)
);
// Create one item validator
const create = [
  body("name")
    .exists({ checkNull: true, checkFalsy: true })
    .withMessage("name is missing.")
 ];
export default create;

and for the collection:

// Validator for creating multiple items
export const createCollection = [
  body("items")
    .exists({ checkNull: true, checkFalsy: true })
    .withMessage("items are missing.")


In the validator for creating a collection of items, I want to validate that each item in the array passes the single item validation.

based on a github thread here, I thought I could do:

export const createCollection = [
  body("items")
    .exists({ checkNull: true, checkFalsy: true })
    .withMessage("items are missing."),
  check("items.*.name")
    .exists()
    .withMessage("name is missing.")

This is working as expected but I would like to reuse the validation for creating a single item instead of copying the validation. For example, something like

check("items.*.name")
    .useTheValidatorFromCreatItem ... 

Example payload:

{
    "items": [
        {
            "noname": "" # this will fail because name is missing
        },
        {
            "name": "test2"
        }
    ]
}
0 Answers
Related