Задать вопрос
Контакты

Достижения

Все достижения (1)

Наибольший вклад в теги

Все теги (9)

Лучшие ответы пользователя

Все ответы (6)
  • Как вернуть сервис в кастомном валидаторе nestjs?

    alex_romanov116
    @alex_romanov116
    Web-developer
    1)
    import {useContainer, Validator} from "class-validator";
    
    useContainer(Container);

    2) используем useContainer из nest
    async function bootstrap() {
      const app = await NestFactory.create(AppModule);
      useContainer(app.select(AppModule), { fallbackOnErrors: true });
    ...}

    3) навешиваем декоратор injectable
    import {ValidatorConstraint, ValidatorConstraintInterface} from 'class-validator';
    import {UsersService} from './user.service';
    import {Injectable} from '@nestjs/common';
    
    @ValidatorConstraint({ name: 'isUserAlreadyExist', async: true })
    @Injectable() // this is needed in order to the class be injected into the module
    export class IsUserAlreadyExist implements ValidatorConstraintInterface {
        constructor(protected readonly usersService: UsersService) {}
    
        async validate(text: string) {
            const user = await this.usersService.findOne({
                email: text
            });
            return !user;
        }
    }


    4) и провайдим constraint
    @Module({
        controllers: [UsersController],
        providers: [IsUserAlreadyExist, UsersService],
        imports: [],
        exports: []
    })
    export class UserModule {
    }
    Ответ написан
    Комментировать

Лучшие вопросы пользователя

Все вопросы (11)