generated from yandeu/phaser-project-template
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUser.ts
98 lines (79 loc) · 2.66 KB
/
User.ts
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
96
97
98
import { User, Prisma } from "@prisma/client";
import bcrypt from "bcrypt";
import DbService from "~/server/services/DbService";
class UserService extends DbService {
private saltRounds = 8;
exclude<User, Key extends keyof User>(user: User, keys: Key[]): Omit<User, Key> {
const omitedUser = { ...user };
for (let key of keys) {
delete omitedUser[key];
}
return omitedUser;
}
excludeMany<User, Key extends keyof User>(users: User[], keys: Key[]): Omit<User, Key>[] {
const omitedUsers = users.map((user) => this.exclude(user, keys));
return omitedUsers;
}
async getAll(): Promise<User[]> {
return this.db.user.findMany();
}
async getById(id: User["id"]): Promise<User | null> {
return this.db.user.findUnique({
where: {
id,
},
});
}
async getByEmail(email: User["email"]): Promise<User | null> {
return this.db.user.findUnique({
where: {
email,
},
});
}
async create(userData: Prisma.UserUncheckedCreateInput): Promise<User> {
const { password } = userData;
if (!password) {
throw Error("Password field was not provided");
}
const hashedPassword = await this.hashPassword(password);
userData.password = hashedPassword;
return this.db.user.create({
data: userData,
});
}
async update(id: User["id"], userData: Prisma.UserUncheckedUpdateInput): Promise<User> {
const { password } = userData;
if (typeof password === "string") {
const hashedPassword = await this.hashPassword(password);
userData.password = hashedPassword;
}
userData.updatedAt = new Date().toJSON();
return this.db.user.update({
where: {
id,
},
data: userData,
});
}
async delete(id: User["id"]): Promise<User> {
return this.db.user.delete({
where: {
id,
},
});
}
async hashPassword(password: string): Promise<string> {
return bcrypt.hash(String(password), this.saltRounds);
}
async comparePasswordByUser(user: User, password: string): Promise<boolean> {
if (!user) return false;
return bcrypt.compare(password, user.password);
}
async comparePasswordById(id: User["id"], password: string): Promise<boolean> {
const user = await this.getById(id);
if (!user) return false;
return await this.comparePasswordByUser(user, password);
}
}
export default UserService;