initial
This commit is contained in:
42
apps/backend/src/common/security/validation.pipe.ts
Normal file
42
apps/backend/src/common/security/validation.pipe.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
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,
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user