79166729

Date: 2024-11-07 13:50:09
Score: 3
Natty:
Report link

Since checkSchema(...) returns an object with all the validation rules (as functions) and run function, one can achieve the dynamic schema validation as follows:

const express = require('express');
const { checkSchema } = require('express-validator');
const router = express.Router();

const BaseSchema = {
    Type: {
        in: 'body',
        notEmpty: {
            errorMessage: "'Type' has to be provided in body"
        }
    }
};
const validateSchemaDynamically = () => async (req, res, next) => {
    // to choose the schema dynamically, we need the type
    const { Type } = req.body;
    switch (Type) {
        case 'A':
            const schema = {
                ...BaseSchema,
                SomeData: {
                    in: 'body',
                    notEmpty: {
                        errorMessage: "'SomeData' has to be provided in body"
                    },
                    isJSON: {
                        errorMessage: "'SomeData' has to be JSON"
                    }
                }
            };

            await checkSchema(schema).run(req);
            return next();
        default:
            await checkSchema(BaseSchema).run(req);
            return next();
    }
};

router.post(
    '/my-endpoint',
    validateSchemaDynamically(),
    handleValidationErrors(), // middleware to check (and handle) validation errors
    async (req, res) => {
        console.log('Business logic here...');
        return res.status(202).send();
    }
);

PS: Please feel free to provide feedback. Answer the question if you know a better way so that we all can learn. Especially, I would appreciate if experts can answer whether this is the right way or not. I wrote some unit test and it seems to do the job, but maybe there is something I am missing?

Reasons:
  • Blacklisted phrase (1.5): would appreciate
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: meakgoz