Improve error handling structure in user module

master
nicekid1 2 months ago
parent c1149c035c
commit 6308630b4b
  1. 1
      src/admin/admin.controller.ts
  2. 11
      src/admin/admin.service.ts
  3. 11
      src/users/users.controller.ts
  4. 80
      src/users/users.service.ts

@ -1,6 +1,5 @@
import { Controller, Get, Post, Body, Request, Put, UseGuards } from "@nestjs/common"; import { Controller, Get, Post, Body, Request, Put, UseGuards } from "@nestjs/common";
import { AdminService } from "./admin.service"; import { AdminService } from "./admin.service";
import { Admin } from "./entities/admin.entity";
import { CreateAdminDto } from "./dto/create-Admin.dto"; import { CreateAdminDto } from "./dto/create-Admin.dto";
import { LoginAdminDto } from "./dto/login-Admin.dto"; import { LoginAdminDto } from "./dto/login-Admin.dto";
import { UpdateUserDto } from "./dto/update-user.dto"; import { UpdateUserDto } from "./dto/update-user.dto";

@ -66,17 +66,20 @@ export class AdminService {
} }
} }
//edit admin profile method //edit admin profile method
async editAdminProfile(userId: number, updateAdminDto: UpdateUserDto): Promise<{ message }> { async editAdminProfile(userId: number, updateAdminDto: UpdateUserDto) {
try { try {
const user = await this.adminModel.findOne({ where: { id: userId } }); let user = await this.adminModel.findOne({ where: { id: userId } });
if (!user) { if (!user) {
throw new Error("Admin not found"); throw new Error("Admin not found");
} }
await user.update(updateAdminDto); await user.update(updateAdminDto);
user = await this.adminModel.findOne({
return { message: "admin account updated successful" }; where: { id: userId },
attributes: { exclude: ["password"] },
});
return { message: "user account updated successful", user };
} catch (error) { } catch (error) {
throw new Error(`An error occurred while updating admin: ${error.message}`); throw new Error(`An error occurred while updating admin: ${error.message}`);
} }

@ -1,4 +1,4 @@
import { Controller, Post, Body, UseGuards, Get, Request, Put } from "@nestjs/common"; import { Controller, Post, Body, UseGuards, Get, Request, Put, Param } from "@nestjs/common";
import { UsersService } from "./users.service"; import { UsersService } from "./users.service";
import { User } from "./entities/user.entity"; import { User } from "./entities/user.entity";
import { CreateUserDto } from "./dto/create-user.dto"; import { CreateUserDto } from "./dto/create-user.dto";
@ -12,7 +12,7 @@ export class UsersController {
constructor(private readonly usersService: UsersService) {} constructor(private readonly usersService: UsersService) {}
//register as user //register as user
@Post("register") @Post("register")
async register(@Body() createUserDto: CreateUserDto): Promise<User> { async register(@Body() createUserDto: CreateUserDto): Promise<{message}> {
return this.usersService.register(createUserDto); return this.usersService.register(createUserDto);
} }
//login as user //login as user
@ -31,7 +31,7 @@ export class UsersController {
//edit user profile //edit user profile
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Put() @Put()
async editProfile(@Request() req, @Body() updateUserDto: UpdateUserDto): Promise<User> { async editProfile(@Request() req, @Body() updateUserDto: UpdateUserDto) {
const userId = req.user.id; const userId = req.user.id;
return this.usersService.editProfile(userId, updateUserDto); return this.usersService.editProfile(userId, updateUserDto);
} }
@ -41,4 +41,9 @@ export class UsersController {
async findAll(): Promise<User[]> { async findAll(): Promise<User[]> {
return this.usersService.findAll(); return this.usersService.findAll();
} }
@UseGuards(RoleGuard)
@Get("users/:id")
async findSpecificUserInfoByUser(@Param("id") id): Promise<User> {
return this.usersService.findSpecificUserInfoByUser(id);
}
} }

@ -1,4 +1,4 @@
import { HttpException, HttpStatus, Injectable, UnauthorizedException, BadRequestException, NotFoundException } from "@nestjs/common"; import { HttpException, HttpStatus, Injectable, UnauthorizedException, BadRequestException, NotFoundException, UseGuards } from "@nestjs/common";
import { InjectModel } from "@nestjs/sequelize"; import { InjectModel } from "@nestjs/sequelize";
import { User } from "./entities/user.entity"; import { User } from "./entities/user.entity";
import * as bcrypt from "bcrypt"; import * as bcrypt from "bcrypt";
@ -17,38 +17,38 @@ export class UsersService {
) {} ) {}
// Register method // Register method
async register(createUserDto: CreateUserDto): Promise<User> { async register(createUserDto: CreateUserDto): Promise<{ message }> {
try { try {
createUserDto.password = await bcrypt.hash(createUserDto.password, parseInt(process.env.BCRYPT_SALT_ROUNDS || "10", 10)); createUserDto.password = await bcrypt.hash(createUserDto.password, parseInt(process.env.BCRYPT_SALT_ROUNDS || "10", 10));
const userExists = await this.userModel.findOne({ const userExists = await this.userModel.findOne({
where: { email: createUserDto.email }, where: { email: createUserDto.email },
}); });
if (userExists) { if (userExists) {
throw new BadRequestException("Email already exists"); throw new BadRequestException("Email is already registered.");
} }
const user = await this.userModel.create(createUserDto); const user = await this.userModel.create(createUserDto);
return user; return { message: "user registered successful" };
} catch (error) { } catch (error) {
throw new HttpException(`An error occurred: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR); if (error instanceof HttpException) {
throw error;
}
throw new HttpException("An unexpected error occurred. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
// Login method // Login method
async login(loginUserDto: LoginUserDto): Promise<{ token: string }> { async login(loginUserDto: LoginUserDto): Promise<{ token: string }> {
try {
const user = await this.userModel.findOne({ const user = await this.userModel.findOne({
where: { email: loginUserDto.email }, where: { email: loginUserDto.email },
}); });
if (!user) { if (!user) {
throw new UnauthorizedException("Invalid email or password"); throw new UnauthorizedException("Invalid email or password.");
} }
const passwordMatch = await bcrypt.compare(loginUserDto.password, user.password); const passwordMatch = await bcrypt.compare(loginUserDto.password, user.password);
if (!passwordMatch) { if (!passwordMatch) {
throw new UnauthorizedException("Invalid email or password"); throw new UnauthorizedException("Invalid email or password.");
} }
const token = this.jwtService.sign( const token = this.jwtService.sign(
{ id: user.id, role: user.role }, { id: user.id, role: user.role },
{ {
@ -56,44 +56,76 @@ export class UsersService {
expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h", expiresIn: this.configService.get<string | number>("JWT_EXPIRES") || "1h",
}, },
); );
return { token }; return { token };
} catch (error) {
if (error instanceof HttpException) {
throw error;
}
throw new HttpException("An unexpected error occurred. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
//get information user method //get information user method
async getProfile(userId: number): Promise<User> { async getProfile(userId: number): Promise<User> {
try {
const user = await this.userModel.findOne({ const user = await this.userModel.findOne({
where: { id: userId }, where: { id: userId },
attributes: { exclude: ["password"] }, attributes: { exclude: ["password"] },
}); });
if (!user) { if (!user) {
throw new Error("User not found"); throw new HttpException("User not found.", HttpStatus.NOT_FOUND);
} }
return user; return user;
} catch (error) {
throw new HttpException("An unexpected error occurred. Please try again later.", HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
//edit profile user method //edit profile user method
async editProfile(userId: number, updateUserDto: UpdateUserDto) { async editProfile(userId: number, updateUserDto: UpdateUserDto) {
const user = await this.userModel.findOne({ where: { id: userId } }); try {
let user = await this.userModel.findOne({ where: { id: userId } });
if (!user) { if (!user) {
throw new NotFoundException("User not found"); throw new NotFoundException('User not found.');
} }
if (updateUserDto.password) { if (updateUserDto.password) {
updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10); updateUserDto.password = await bcrypt.hash(updateUserDto.password, 10);
} }
await user.update(updateUserDto); await user.update(updateUserDto);
user = await this.userModel.findOne({
return user; where: { id: userId },
attributes: { exclude: ['password'] },
});
return { message: 'User account updated successfully.', user };
} catch (error) {
throw new HttpException(
'An unexpected error occurred. Please try again later.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
} }
//get users list //get users list
async findAll(): Promise<User[]> { async findAll(): Promise<User[]> {
try { try {
return await this.userModel.findAll(); return await this.userModel.findAll();
} catch (error) { } catch (error) {
throw new Error("An error occurred while fetching users"); throw new HttpException(
'An unexpected error occurred while fetching users.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
//get users list
async findSpecificUserInfoByUser(userId: number): Promise<User> {
try {
const user = await this.userModel.findByPk(userId);
if (!user) {
throw new HttpException('User not found.', HttpStatus.NOT_FOUND);
}
return user;
} catch (error) {
throw new HttpException(
'An unexpected error occurred while fetching user information.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
} }
} }
} }

Loading…
Cancel
Save