Update try-catch handling in user register and login functionality

master
nicekid1 2 months ago
parent 3c216fa12a
commit 69c0a65ad5
  1. 13
      src/users/users.controller.ts
  2. 39
      src/users/users.service.ts

@ -1,21 +1,20 @@
import { Controller, Post, Body, Res, UseGuards, Get } from "@nestjs/common"; import { Controller, Post, Body, Res, UseGuards, Get } from "@nestjs/common";
import { UsersService } from "./users.service"; import { UsersService } from "./users.service";
import { Response } from "express"; import { User } from "./entities/user.entity";
import { JwtAuthGuard } from "src/guard/auth.guard";
@Controller("users") @Controller("user")
export class UsersController { export class UsersController {
constructor(private readonly usersService: UsersService) {} constructor(private readonly usersService: UsersService) {}
@Post("register") @Post("register")
async register(@Body() body: { email: string; password: string }, @Res() res: Response): Promise<Response> { async register(@Body() body: { email: string; password: string }):Promise<User> {
const { email, password } = body; const { email, password } = body;
return this.usersService.register(email, password, res); return this.usersService.register(email, password);
} }
@Post("login") @Post("login")
async login(@Body() body: { email: string; password: string }, @Res() res: Response): Promise<Response> { async login(@Body() body: { email: string; password: string }):Promise<{token}> {
const { email, password } = body; const { email, password } = body;
return this.usersService.login(email, password, res); return this.usersService.login(email, password);
} }
} }

@ -1,8 +1,7 @@
import { Injectable, UnauthorizedException } from "@nestjs/common"; import { HttpException, HttpStatus, Injectable, UnauthorizedException, BadRequestException } 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";
import { Response } from "express";
import { JwtService } from '@nestjs/jwt'; import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config'; import { ConfigService } from '@nestjs/config';
@ -15,13 +14,16 @@ export class UsersService {
) {} ) {}
// Register method // Register method
async register(email: string, password: string, res: Response): Promise<Response> { async register(email: string, password: string): Promise<User> {
if (!email) throw new BadRequestException("Email should be entered");
if (!password) throw new BadRequestException("Password should be entered");
try { try {
const hashedPassword = await bcrypt.hash(password, 10); const hashedPassword = await bcrypt.hash(password, 10);
const userExists = await this.userModel.findOne({ where: { email } }); const userExists = await this.userModel.findOne({ where: { email } });
if (userExists) { if (userExists) {
return res.status(400).json({ message: "Email is already taken" }); throw new BadRequestException('Email already exists');
} }
const user = await this.userModel.create({ const user = await this.userModel.create({
@ -29,21 +31,17 @@ export class UsersService {
password: hashedPassword, password: hashedPassword,
}); });
return res.status(201).json({ return user;
message: "Account created successfully!",
user: { id: user.id, email: user.email },
});
} catch (error) { } catch (error) {
return res.status(500).json({ throw new HttpException(`An error occurred: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
message: "Failed to create account. Please try again later.",
error: error.message,
});
} }
} }
// Login method // Login method
async login(email: string, password: string, res: Response): Promise<Response> { async login(email: string, password: string): Promise<{ token: string }> {
try { if (!email) throw new BadRequestException("Email should be entered");
if (!password) throw new BadRequestException("Password should be entered");
const user = await this.userModel.findOne({ const user = await this.userModel.findOne({
where: { email }, where: { email },
}); });
@ -56,7 +54,7 @@ export class UsersService {
throw new UnauthorizedException("Invalid email or password"); throw new UnauthorizedException("Invalid email or password");
} }
const token = await this.jwtService.sign( const token = this.jwtService.sign(
{ id: user.id }, { id: user.id },
{ {
secret: this.configService.get<string>("JWT_SECRET"), secret: this.configService.get<string>("JWT_SECRET"),
@ -64,15 +62,6 @@ export class UsersService {
}, },
); );
return res.status(200).json({ return { token };
message: "Login successful",
token,
});
} catch (error) {
return res.status(500).json({
message: "Internal server error",
error: error.message,
});
}
} }
} }

Loading…
Cancel
Save