43 lines
1.2 KiB
TypeScript
43 lines
1.2 KiB
TypeScript
import { ValidationPipe } from '@nestjs/common';
|
|
import type { ValidationError } from '@nestjs/common';
|
|
import { ErrorCode } from '../errors/error-codes';
|
|
import { ApiError, type ValidationErrorDetail } from '../errors/api-error';
|
|
|
|
function flattenValidation(
|
|
errors: ValidationError[],
|
|
parent = '',
|
|
): ValidationErrorDetail[] {
|
|
return errors.flatMap((error) => {
|
|
const field = parent ? `${parent}.${error.property}` : error.property;
|
|
const own = error.constraints
|
|
? [
|
|
{
|
|
field,
|
|
messages: Object.values(error.constraints).map(
|
|
() => 'Ungueltiger Wert.',
|
|
),
|
|
},
|
|
]
|
|
: [];
|
|
return [...own, ...flattenValidation(error.children ?? [], field)];
|
|
});
|
|
}
|
|
|
|
export function createValidationPipe(): ValidationPipe {
|
|
return new ValidationPipe({
|
|
whitelist: true,
|
|
forbidNonWhitelisted: true,
|
|
transform: true,
|
|
transformOptions: { enableImplicitConversion: false },
|
|
exceptionFactory: (errors) => {
|
|
const validation = flattenValidation(errors);
|
|
return new ApiError(
|
|
ErrorCode.ValidationFailed,
|
|
'Bitte pruefen Sie die markierten Felder.',
|
|
400,
|
|
validation,
|
|
);
|
|
},
|
|
});
|
|
}
|