@Speakermen

Как можно улучшить код?

Вижу дубликаты
this.user = await this.usersService.findOne({ email: createAuthDto.email });


но как можно улучшить подобный код использовать Фабрику, Стратегию? Есть ещё идея разнести ещё на одни отдельные модули

AuthModule
--LoginModule REST
--RegisterModule REST

import {
  BadRequestException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { User } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { UsersService } from '../users/users.service';
import { CreateLoginDto } from './dto/create-login.dto';
import { CreateAuthDto } from './index';

@Injectable()
export class AuthService {
  private user: User;

  public constructor(private readonly usersService: UsersService) {}

  private async validateEmail(createAuthDto): Promise<void> {
    this.user = await this.usersService.findOne({ email: createAuthDto.email });

    if (this.user && this.user.email === createAuthDto.email) {
      throw new BadRequestException('Choose another email');
    }

    createAuthDto.password = await bcrypt.hash(createAuthDto.password, 12);
  }

  private async validatePassport(createLoginDto): Promise<void> {
    this.user = await this.usersService.findOne({
      email: createLoginDto.email,
    });

    if (
      !this.user ||
      !(await bcrypt.compare(createLoginDto.password, this.user.password))
    ) {
      throw new UnauthorizedException('Email or password is incorrect');
    }
  }

  public async register(createAuthDto: CreateAuthDto): Promise<User> {
    await this.validateEmail(createAuthDto);

    return await this.usersService.create(createAuthDto);
  }

  public async login(createLoginDto: CreateLoginDto): Promise<User> {
    await this.validatePassport(createLoginDto);

    return this.user;
  }
}
  • Вопрос задан
  • 70 просмотров
Решения вопроса 2
Aetae
@Aetae Куратор тега TypeScript
Тлен
Про паттерны-фигаторны ничего не скажу, а вот то что метод начинающийся на validate не должен ничего никуда писать - это факт.)
Ответ написан
Комментировать
private async validateEmail(createAuthDto): Promise

private async validatePassport(createLoginDto): Promise

Указать типы для createAuthDto и createLoginDto

if (this.user && this.user.email === createAuthDto.email) {
throw new BadRequestException('Choose another email');
}

Ну и думаю данную проверку(this.user.email === createAuthDto.email) можно убрать, вы же делаете выборку из usersService по email, поэтому если был получен не null, то пользователь с таким email уже существует.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

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