Skip to content

Instantly share code, notes, and snippets.

@andrevandal
Created April 20, 2023 15:40
Show Gist options
  • Save andrevandal/05f6ef1c214324f39391ffd8f466bcb3 to your computer and use it in GitHub Desktop.
Save andrevandal/05f6ef1c214324f39391ffd8f466bcb3 to your computer and use it in GitHub Desktop.
refactor middleware validation from @lukinhas711
import { RequestHandler } from 'express';
import { ValidationError, ObjectSchema, Maybe, AnyObject } from 'yup';
import { StatusCodes } from 'http-status-codes';
type TProperty = 'body' | 'header' | 'params' | 'query';
type TGetSchema = <T extends Maybe<AnyObject>>(schema: ObjectSchema<T>) => ObjectSchema<any>;
type TAllSchemas = Record<TProperty, ObjectSchema<any>>;
type TGetAllSchemas = (getSchema: TGetSchema) => Partial<TAllSchemas>;
type TValidation = (getAllSchemas: TGetAllSchemas) => RequestHandler;
export const validation: TValidation = (getAllSchemas) => async (req, res, next) => {
const schemas = getAllSchemas(schema => schema);
const listErrors: Record<string, Record<string, string>> = {};
const schemaValidations = Object.entries(schemas).map(async ([key, schema]) => {
try {
await schema.validate(req[key as TProperty], { abortEarly: false });
} catch (err) {
const yupError = err as ValidationError;
const errors: Record<string, string> = {};
yupError.inner.forEach(error => {
if (!error.path) return;
errors[error.path] = error.message;
});
listErrors[key] = errors;
}
});
await Promise.all(schemaValidations);
if (Object.entries(listErrors).length === 0) {
next();
} else {
res.status(StatusCodes.BAD_REQUEST).json({ errors: listErrors });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment