File size: 2,815 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
import { Injectable, InternalServerErrorException } from "@nestjs/common";
import { Prisma, User } from "@prisma/client";
import { UserWithSecrets } from "@reactive-resume/dto";
import { ErrorMessage } from "@reactive-resume/utils";
import { PrismaService } from "nestjs-prisma";
import { StorageService } from "../storage/storage.service";
@Injectable()
export class UserService {
constructor(
private readonly prisma: PrismaService,
private readonly storageService: StorageService,
) {}
async findOneById(id: string): Promise<UserWithSecrets> {
const user = await this.prisma.user.findUniqueOrThrow({
where: { id },
include: { secrets: true },
});
if (!user.secrets) {
throw new InternalServerErrorException(ErrorMessage.SecretsNotFound);
}
return user;
}
async findOneByIdentifier(identifier: string): Promise<UserWithSecrets | null> {
const user = await (async (identifier: string) => {
// First, find the user by email
const user = await this.prisma.user.findUnique({
where: { email: identifier },
include: { secrets: true },
});
// If the user exists, return it
if (user) return user;
// Otherwise, find the user by username
// If the user doesn't exist, throw an error
return this.prisma.user.findUnique({
where: { username: identifier },
include: { secrets: true },
});
})(identifier);
return user;
}
async findOneByIdentifierOrThrow(identifier: string): Promise<UserWithSecrets> {
const user = await (async (identifier: string) => {
// First, find the user by email
const user = await this.prisma.user.findUnique({
where: { email: identifier },
include: { secrets: true },
});
// If the user exists, return it
if (user) return user;
// Otherwise, find the user by username
// If the user doesn't exist, throw an error
return this.prisma.user.findUniqueOrThrow({
where: { username: identifier },
include: { secrets: true },
});
})(identifier);
return user;
}
create(data: Prisma.UserCreateInput): Promise<UserWithSecrets> {
return this.prisma.user.create({ data, include: { secrets: true } });
}
updateByEmail(email: string, data: Prisma.UserUpdateArgs["data"]): Promise<User> {
return this.prisma.user.update({ where: { email }, data });
}
async updateByResetToken(
resetToken: string,
data: Prisma.SecretsUpdateArgs["data"],
): Promise<void> {
await this.prisma.secrets.update({ where: { resetToken }, data });
}
async deleteOneById(id: string): Promise<void> {
await Promise.all([
this.storageService.deleteFolder(id),
this.prisma.user.delete({ where: { id } }),
]);
}
}
|