|
1 |
| -import { ArgumentMetadata, PipeTransform } from '@nestjs/common'; |
2 |
| -import { ValidationOptions } from 'class-validator'; |
| 1 | +import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common'; |
| 2 | +import { |
| 3 | + ValidationArguments, |
| 4 | + ValidationOptions, |
| 5 | + ValidatorConstraint, |
| 6 | + ValidatorConstraintInterface, |
| 7 | +} from 'class-validator'; |
3 | 8 | import { ValidationException } from '~/core/validation';
|
4 | 9 | import { isValidId } from '../generate-id';
|
| 10 | +import { ID } from '../id-field'; |
5 | 11 | import { ValidateBy } from './validateBy';
|
6 | 12 |
|
7 | 13 | export const IsId = (validationOptions?: ValidationOptions) =>
|
8 |
| - ValidateBy( |
9 |
| - { |
10 |
| - name: 'IsId', |
11 |
| - validator: { |
12 |
| - validate: isValidId, |
13 |
| - defaultMessage: () => |
14 |
| - validationOptions?.each |
15 |
| - ? 'Each value in $property must be a valid ID' |
16 |
| - : 'Invalid ID', |
17 |
| - }, |
18 |
| - }, |
19 |
| - validationOptions, |
20 |
| - ); |
| 14 | + ValidateBy(ValidIdConstraint, { |
| 15 | + message: validationOptions?.each |
| 16 | + ? 'Each value in $property must be a valid ID' |
| 17 | + : 'Invalid ID', |
| 18 | + ...validationOptions, |
| 19 | + }); |
| 20 | + |
| 21 | +@Injectable() |
| 22 | +export class IdResolver { |
| 23 | + async resolve(value: ID): Promise<ID> { |
| 24 | + return value; |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +@Injectable() |
| 29 | +@ValidatorConstraint({ name: 'IsId', async: true }) |
| 30 | +export class ValidIdConstraint implements ValidatorConstraintInterface { |
| 31 | + constructor(private readonly resolver: IdResolver) {} |
21 | 32 |
|
| 33 | + async validate(value: unknown, args: ValidationArguments) { |
| 34 | + if (isValidId(value)) { |
| 35 | + (args.object as any)[args.property] = await this.resolver.resolve(value); |
| 36 | + return true; |
| 37 | + } |
| 38 | + return false; |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +@Injectable() |
22 | 43 | export class ValidateIdPipe implements PipeTransform {
|
| 44 | + constructor(private readonly resolver: IdResolver) {} |
| 45 | + |
23 | 46 | transform(id: unknown, metadata: ArgumentMetadata) {
|
24 |
| - if (id == null || isValidId(id)) { |
25 |
| - return id; |
| 47 | + if (id == null) { |
| 48 | + return null; |
| 49 | + } |
| 50 | + if (isValidId(id)) { |
| 51 | + return this.resolver.resolve(id); |
26 | 52 | }
|
27 | 53 | throw new ValidationException([
|
28 | 54 | {
|
|
0 commit comments