import { ConflictException, Injectable, NotFoundException, } from '@nestjs/common'; import { Prisma, User } from '@prisma/client'; import * as bcrypt from 'bcrypt'; import { PrismaService } from '../prisma/prisma.service'; import { CreateUserDto } from './dto/create-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; import { UserResponseDto } from './dto/user-response.dto'; const BCRYPT_SALT_ROUNDS = 12; const UNIQUE_CONSTRAINT_VIOLATION = 'P2002'; const RECORD_NOT_FOUND = 'P2025'; @Injectable() export class UsersService { constructor(private readonly prisma: PrismaService) {} async create(dto: CreateUserDto): Promise { const hashedPassword = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS); try { const user = await this.prisma.user.create({ data: { firstName: dto.firstName, lastName: dto.lastName, email: dto.email, password: hashedPassword, }, }); return this.toResponse(user); } catch (error) { if ( error instanceof Prisma.PrismaClientKnownRequestError && error.code === UNIQUE_CONSTRAINT_VIOLATION ) { throw new ConflictException( `Un utilisateur avec l'email "${dto.email}" existe deja`, ); } throw error; } } async findAll(): Promise { const users = await this.prisma.user.findMany({ orderBy: { id: 'asc' } }); return users.map((user) => this.toResponse(user)); } async findOne(id: number): Promise { const user = await this.prisma.user.findUnique({ where: { id } }); if (!user) throw new NotFoundException(`Utilisateur ${id} introuvable`); return this.toResponse(user); } async update(id: number, dto: UpdateUserDto): Promise { const data: Prisma.UserUpdateInput = { ...dto }; if (dto.password) { data.password = await bcrypt.hash(dto.password, BCRYPT_SALT_ROUNDS); } try { const user = await this.prisma.user.update({ where: { id }, data }); return this.toResponse(user); } catch (error) { if (error instanceof Prisma.PrismaClientKnownRequestError) { if (error.code === RECORD_NOT_FOUND) throw new NotFoundException(`Utilisateur ${id} introuvable`); if (error.code === UNIQUE_CONSTRAINT_VIOLATION) { throw new ConflictException( `Un utilisateur avec l'email "${dto.email}" existe deja`, ); } } throw error; } } async remove(id: number): Promise { try { await this.prisma.user.delete({ where: { id } }); } catch (error) { if ( error instanceof Prisma.PrismaClientKnownRequestError && error.code === RECORD_NOT_FOUND ) { throw new NotFoundException(`Utilisateur ${id} introuvable`); } throw error; } } /** Jamais inclure le mot de passe (meme hache) dans une reponse HTTP. */ private toResponse(user: User): UserResponseDto { return { id: user.id, firstName: user.firstName, lastName: user.lastName, email: user.email, createdAt: user.createdAt, updatedAt: user.updatedAt, }; } }