-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathusers.service.ts
64 lines (47 loc) · 2.25 KB
/
users.service.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
import { hash } from 'bcrypt';
import { CreateUserDto } from '@dtos/users.dto';
import { HttpException } from '@exceptions/HttpException';
import { User } from '@interfaces/users.interface';
import userModel from '@models/users.model';
import { isEmpty } from '@utils/util';
class UserService {
public users = userModel;
public async findAllUser(): Promise<User[]> {
const users: User[] = await this.users.find();
return users;
}
public async findUserById(userId: string): Promise<User> {
if (isEmpty(userId)) throw new HttpException(400, "UserId is empty");
const findUser: User = await this.users.findOne({ _id: userId });
if (!findUser) throw new HttpException(409, "User doesn't exist");
return findUser;
}
public async createUser(userData: CreateUserDto): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "userData is empty");
const findUser: User = await this.users.findOne({ email: userData.email });
if (findUser) throw new HttpException(409, `This email ${userData.email} already exists`);
const hashedPassword = await hash(userData.password, 10);
const createUserData: User = await this.users.create({ ...userData, password: hashedPassword });
return createUserData;
}
public async updateUser(userId: string, userData: CreateUserDto): Promise<User> {
if (isEmpty(userData)) throw new HttpException(400, "userData is empty");
if (userData.email) {
const findUser: User = await this.users.findOne({ email: userData.email });
if (findUser && findUser._id != userId) throw new HttpException(409, `This email ${userData.email} already exists`);
}
if (userData.password) {
const hashedPassword = await hash(userData.password, 10);
userData = { ...userData, password: hashedPassword };
}
const updateUserById: User = await this.users.findByIdAndUpdate(userId, { userData });
if (!updateUserById) throw new HttpException(409, "User doesn't exist");
return updateUserById;
}
public async deleteUser(userId: string): Promise<User> {
const deleteUserById: User = await this.users.findByIdAndDelete(userId);
if (!deleteUserById) throw new HttpException(409, "User doesn't exist");
return deleteUserById;
}
}
export default UserService;