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 async findAllUser ( ) { const users = await userModel . find ( ) ; return users ; } public async findUserById ( userId ) { if ( isEmpty ( userId ) ) throw new HttpException ( 400 , "You're not userId" ) ; const findUser = await userModel . findOne ( { _id : userId } ) ; if ( ! findUser ) throw new HttpException ( 409 , "You're not user" ) ; return findUser ; } public async createUser ( userData ) { if ( isEmpty ( userData ) ) throw new HttpException ( 400 , "You're not userData" ) ; const findUser = await userModel . findOne ( { email : userData . email } ) ; if ( findUser ) throw new HttpException ( 409 , `You're email ${ userData . email } already exists` ) ; const hashedPassword = await hash ( userData . password , 10 ) ; const createUserData = await userModel . create ( { ... userData , password : hashedPassword } ) ; return createUserData ; } public async updateUser ( userId , userData ) { if ( isEmpty ( userData ) ) throw new HttpException ( 400 , "You're not userData" ) ; if ( userData . email ) { const findUser = await userModel . findOne ( { email : userData . email } ) ; if ( findUser && findUser . _id != userId ) throw new HttpException ( 409 , `You're email ${ userData . email } already exists` ) ; } if ( userData . password ) { const hashedPassword = await hash ( userData . password , 10 ) ; userData = { ... userData , password : hashedPassword } ; } const updateUserById = await userModel . findByIdAndUpdate ( userId , { userData } ) ; if ( ! updateUserById ) throw new HttpException ( 409 , "You're not user" ) ; return updateUserById ; } public async deleteUser ( userId ) { const deleteUserById = await userModel . findByIdAndDelete ( userId ) ; if ( ! deleteUserById ) throw new HttpException ( 409 , "You're not user" ) ; return deleteUserById ; } } export default UserService ;