如何为自定义类验证器验证装饰器强制执行某些执行顺序

时间:2021-06-03 07:07:00

标签: node.js nestjs class-validator

问题来了。请看看这个 DTO:

this.dataService.getData(0, this.maxResults).subscribe((data, status_code)=>{
      this.data = data;
      this.total = data.totalCount;
      this.pages = Math.ceil(this.total / this.maxResults);
});

export class CancelFightEventDto implements Identifiable { @IsNumber() @Type(() => Number) @IsNotEmpty() @Min(1) @Validate(IsFightEventNotInStatus, [EFightEventStatus.ONGOING, EFightEventStatus.FINISHED]) @Validate(FightEventBelongsToArena) id: number; @Validate(IsLocationProvider) @IsNumber() @Type(() => Number) userId: number; } 属性用两个装饰器装饰,如下所示:

id
@ValidatorConstraint({ name: 'FightEventBelongsToArena', async: false })
@Injectable()
export class FightEventBelongsToArena implements ValidatorConstraintInterface {
    constructor(
        @InjectRepository(UserEntity)
        private readonly usersRepository: Repository<UserEntity>,
    ) {}

    public async validate(id: number, args: FightEventBelongsToArenaValidationArguments): Promise<boolean> {
        const [response]: [{[isFound: string]: string}] = (await this.usersRepository.query(
            `
                SELECT
                    COUNT(id) >= 1 AS "isFound"
                FROM
                    fight_events
                WHERE
                    "locationId" IN (
                        SELECT
                            "locationId"
                        FROM
                            users
                        WHERE
                            id = ${args.object.userId}
                    )
                    AND id = ${id};
            `
        ));
        
        if(!response.isFound) throw new ForbiddenException('Not allowed. Reason: Incorrect fight event id.');
        return response.isFound;
    }

};

问题是无法保证这些装饰器的执行顺序,但我需要它始终相同。

0 个答案:

没有答案