I would like to turn the code duplication, in my express-validator ValidationChain’ing, into a simpler map
statement.
Here is my current, working code, that validates all my test string inputs, when I hit the “/account” endpoint:
import { ValidationChain, body } from 'express-validator';
const validateCreateAccount: ValidationChain[] = [
body('accountName')
.exists({ checkNull: true, checkFalsy: true })
.withMessage((_, { path }) => `${path} is required`)
.bail()
.isString()
.withMessage((value, { path }) => `${path} must be a string, received value: ${value}`),
body('country')
.exists({ checkNull: true, checkFalsy: true })
.withMessage((_, { path }) => `${path} is required`)
.bail()
.isString()
.withMessage((value, { path }) => `${path} must be a string, received value: ${value}`),
body('logo')
.exists({ checkNull: true, checkFalsy: true })
.withMessage((_, { path }) => `${path} is required`)
.bail()
.isString()
.withMessage((value, { path }) => `${path} must be a string, received value: ${value}`),
// etc. more fields
];
export default validateCreateAccount;
For input:
{
"accountName": "foo",
"country": "US",
"logo": "https://example.com/logo.png"
}
But what I’d like is something similar to this simplified code:
import { ValidationChain, body } from 'express-validator';
const validationNames: object = {
accountName: 'string',
country: 'string',
logo: 'string',
};
const validateCreateAccount: ValidationChain[] = Object.entries(validationNames)
.map((name, type) => {
const check: ValidationChain = body(name)
.exists({ checkNull: true, checkFalsy: true })
.withMessage((_, { path }) => `${path} is required`)
.bail()
.isString()
.withMessage((value, { path }) => `${path} must be a ${type}, received value: ${value}`);
return check;
});
export default validateCreateAccount;
But this seems to clobber the express-validator path
that is used in the messages, when I hit the endpoint:
"errors": [
{
"type": "field",
"msg": "string is required",
"path": "string",
"location": "body"
},
{
"type": "field",
"msg": "string is required",
"path": "string",
"location": "body"
},
{
"type": "field",
"msg": "string is required",
"path": "string",
"location": "body"
},
]
Puzzling!
How do I use a k:v object of things to validate, and not seemingly overwrite the path
?