【问题标题】:Inject DataSource in ValidatorConstraint gives me undefined in NestJS在 ValidatorConstraint 中注入 DataSource 给我在 NestJS 中未定义
【发布时间】:2022-07-25 15:06:24
【问题描述】:

我想要一个自定义 ValidatorConstraint 来验证表中是否存在具有值的列。我想注入 TypeORM 的 DataSource 来进行查询,但是当我在验证器中创建 this.dataSource 时返回“未定义”。

这是我的 DTO:

import { ApiProperty } from '@nestjs/swagger';
import { IsInt, IsNotEmpty, IsString, Max, Min } from 'class-validator';
import { Exists } from "../../common/decorators/exists.decorator";

export class CreateTeacherReviewDto {

    @ApiProperty()
    @IsNotEmpty()
    @IsInt()
    @Exists(['teacher:id'])
    readonly teacherId: number;
}

这是我的自定义验证器:

import { BadRequestException, Injectable } from '@nestjs/common';
import {
    registerDecorator,
    ValidationArguments,
    ValidationOptions,
    ValidatorConstraint,
    ValidatorConstraintInterface,
} from 'class-validator';
import { DataSource } from "typeorm";

export function Exists(property: any, validationOptions?: ValidationOptions) {
    return (object: any, propertyName: string) => {
        registerDecorator({
            target: object.constructor,
            propertyName,
            options: validationOptions,
            constraints: [property],
            validator: ExistsConstraint,
        });
    };
}

@ValidatorConstraint({ name: 'Exists', async: true })
@Injectable()
export class ExistsConstraint implements ValidatorConstraintInterface {
    constructor(protected dataSource: DataSource) {}

    async validate(value: number | string, args: ValidationArguments) {
        const { constraints } = args;
        if (constraints.length === 0) {
            throw new BadRequestException(`Failed validating ${value} exists.`);
        }

        const str = constraints[0][0].split(':');
        const tableName = str[0];
        const columnName = str[1];

        console.log(this.dataSource); // In this line returns me undefined

        return false;

    }

    defaultMessage(args: ValidationArguments) {
        const { property, value } = args;

        return `${property} ${value} is already taken.`;
    }
}

我在 package.json 中的依赖:

"dependencies": {
        "@nestjs/common": "^8.0.0",
        "@nestjs/config": "^2.1.0",
        "@nestjs/core": "^8.0.0",
        "@nestjs/jwt": "^8.0.1",
        "@nestjs/mapped-types": "*",
        "@nestjs/passport": "^8.2.2",
        "@nestjs/platform-express": "^8.0.0",
        "@nestjs/swagger": "^5.2.1",
        "@nestjs/typeorm": "^8.1.4",
        "bcrypt": "^5.0.1",
        "class-transformer": "^0.5.1",
        "class-validator": "^0.13.2",
        "mysql2": "^2.3.3",
        "passport": "^0.6.0",
        "passport-jwt": "^4.0.0",
        "reflect-metadata": "^0.1.13",
        "rimraf": "^3.0.2",
        "rxjs": "^7.2.0",
        "swagger-ui-express": "^4.4.0",
        "typeorm": "^0.3.6"
    },

还有我的 tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

【问题讨论】:

  • 您能提供一个MCVE 吗?
  • 嗨@l-_-l,我在 DTO 中添加了依赖项、我的 tsconfig 和导入
  • 很好,仍然不是 MCVE,我无法重现该行为:请创建一个 Stackblitz 我会看看

标签: typescript nestjs typeorm


【解决方案1】:

我已经在 SharedModule 中注入 Exist Constraint 作为提供者,它可以工作

【讨论】:

    猜你喜欢
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 1970-01-01
    • 2021-07-10
    • 2020-09-09
    • 2022-01-17
    • 2020-10-30
    相关资源
    最近更新 更多