2022-12-05 10:02:19 +01:00
|
|
|
import { BadRequestException, Injectable } from "@nestjs/common";
|
|
|
|
import { PrismaClientKnownRequestError } from "@prisma/client/runtime";
|
|
|
|
import * as argon from "argon2";
|
|
|
|
import { PrismaService } from "src/prisma/prisma.service";
|
2022-12-05 15:53:24 +01:00
|
|
|
import { CreateUserDTO } from "./dto/createUser.dto";
|
2022-12-05 10:02:19 +01:00
|
|
|
import { UpdateUserDto } from "./dto/updateUser.dto";
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class UserSevice {
|
|
|
|
constructor(private prisma: PrismaService) {}
|
|
|
|
|
|
|
|
async list() {
|
|
|
|
return await this.prisma.user.findMany();
|
|
|
|
}
|
|
|
|
|
|
|
|
async get(id: string) {
|
|
|
|
return await this.prisma.user.findUnique({ where: { id } });
|
|
|
|
}
|
|
|
|
|
2022-12-05 15:53:24 +01:00
|
|
|
async create(dto: CreateUserDTO) {
|
2022-12-05 10:02:19 +01:00
|
|
|
const hash = await argon.hash(dto.password);
|
|
|
|
try {
|
|
|
|
return await this.prisma.user.create({
|
|
|
|
data: {
|
|
|
|
...dto,
|
|
|
|
password: hash,
|
|
|
|
},
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof PrismaClientKnownRequestError) {
|
|
|
|
if (e.code == "P2002") {
|
|
|
|
const duplicatedField: string = e.meta.target[0];
|
|
|
|
throw new BadRequestException(
|
|
|
|
`A user with this ${duplicatedField} already exists`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async update(id: string, user: UpdateUserDto) {
|
|
|
|
try {
|
|
|
|
const hash = user.password && (await argon.hash(user.password));
|
|
|
|
|
|
|
|
return await this.prisma.user.update({
|
|
|
|
where: { id },
|
|
|
|
data: { ...user, password: hash },
|
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
if (e instanceof PrismaClientKnownRequestError) {
|
|
|
|
if (e.code == "P2002") {
|
|
|
|
const duplicatedField: string = e.meta.target[0];
|
|
|
|
throw new BadRequestException(
|
|
|
|
`A user with this ${duplicatedField} already exists`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async delete(id: string) {
|
|
|
|
return await this.prisma.user.delete({ where: { id } });
|
|
|
|
}
|
|
|
|
}
|