Вижу дубликаты
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;
}
}