@Speakermen

Можно ли в express вынести обработку express-validator в DTO?

Как можно вынести в Dto? Без TS плохо, но я не знаю как настроить в express в NestJs он шёл из коробки)

Прохожу курс для тренировки и знакомства с socketa-ми. На Udemy Create a Twitter Clone with Node.js, Socket.IO and MongoDB

router.post(
  '/register',
  body('firstName').not().isEmpty().trim().escape(),
  body('lastName').not().isEmpty().trim().escape(),
  body('username').not().isEmpty().trim().escape(),
  body('email').isEmail(),
  body('password'),
  body('passwordConf').custom((value, { req }) => {
    if (value !== req.body.password) {
      throw new Error('Password confirmation does not match password');
    }

    // Indicates the success of this synchronous custom validator
    return true;
  }),
  (req, res, next) => {
    authService.register();
    console.log(validationResult(req));

    res.render('register', { title: 'Twitter' });
  }
);


Чтобы получилось типа этого

import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const ReqBody = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    return request.body;
  },
);


@UseGuards(LocalAuthGuard)
  @Post('/register')
  async register(
    @ReqBody(new ValidationPipe({ validateCustomDecorators: true }))
    createRegisterDto: CreateRegisterDto,
  ) {
    return this.authService.register(createRegisterDto);
  }


import { IsEmail, IsNotEmpty, MaxLength, MinLength } from 'class-validator';

export class CreateRegisterDto {
  @IsNotEmpty()
  @IsEmail()
  email: string;

  @IsNotEmpty()
  @MinLength(1)
  @MaxLength(255)
  firstName: string;

  @IsNotEmpty()
  @MinLength(1)
  @MaxLength(255)
  lastName: string;

  @IsNotEmpty()
  @MinLength(6)
  @MaxLength(255)
  password: string;
}
  • Вопрос задан
  • 97 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы