feat: Implement AuthService for user registration with detailed field error handling and updated user roles.

This commit is contained in:
pradeepkumar
2025-12-22 11:53:53 +05:30
parent de32edb7ab
commit 5c6ab92056
6 changed files with 447 additions and 74 deletions

71
src/services/api.ts Normal file
View File

@@ -0,0 +1,71 @@
import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';
// API Response types
export interface ApiResponse<T = unknown> {
success: boolean;
data: T;
statusCode?: number;
timestamp?: string;
}
export interface ApiErrorResponse {
success: false;
statusCode: number;
timestamp: string;
path: string;
method: string;
error: string;
message: string | string[];
errors?: Array<{ field: string; errors: string[] }>;
}
// Create axios instance
const api: AxiosInstance = axios.create({
baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1',
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
});
// Request interceptor
api.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// Add auth token if available
if (typeof window !== 'undefined') {
const token = localStorage.getItem('accessToken');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
}
return config;
},
(error: AxiosError) => {
return Promise.reject(error);
}
);
// Response interceptor
api.interceptors.response.use(
(response) => {
return response;
},
(error: AxiosError<ApiErrorResponse>) => {
// Handle common errors
if (error.response) {
const { status } = error.response;
// Handle 401 Unauthorized
if (status === 401) {
if (typeof window !== 'undefined') {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
}
}
}
return Promise.reject(error);
}
);
export default api;

View File

@@ -0,0 +1,146 @@
import api, { ApiResponse, ApiErrorResponse } from './api';
import { AxiosError } from 'axios';
// Types
export interface RegisterRequest {
firstName: string;
lastName?: string;
email: string;
password: string;
role: 'USER' | 'AGENT';
}
export interface LoginRequest {
email: string;
password: string;
}
export interface AuthUser {
id: string;
email: string;
role: string;
firstName?: string;
lastName?: string;
avatar?: string;
}
export interface AuthResponse {
user: AuthUser;
accessToken: string;
refreshToken: string;
}
export interface ForgotPasswordRequest {
email: string;
}
export interface ResetPasswordRequest {
token: string;
password: string;
}
export interface VerifyEmailRequest {
token: string;
}
export interface MessageResponse {
message: string;
}
// Auth Service
class AuthService {
private basePath = '/auth';
async register(data: RegisterRequest): Promise<ApiResponse<AuthResponse>> {
const response = await api.post<ApiResponse<AuthResponse>>(
`${this.basePath}/register`,
data
);
return response.data;
}
async login(data: LoginRequest): Promise<ApiResponse<AuthResponse>> {
const response = await api.post<ApiResponse<AuthResponse>>(
`${this.basePath}/login`,
data
);
return response.data;
}
async forgotPassword(data: ForgotPasswordRequest): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/forgot-password`,
data
);
return response.data;
}
async resetPassword(data: ResetPasswordRequest): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/reset-password`,
data
);
return response.data;
}
async verifyEmail(data: VerifyEmailRequest): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/verify-email`,
data
);
return response.data;
}
async resendVerification(): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(
`${this.basePath}/resend-verification`
);
return response.data;
}
async getCurrentUser(): Promise<ApiResponse<AuthUser>> {
const response = await api.get<ApiResponse<AuthUser>>(`${this.basePath}/me`);
return response.data;
}
async refreshToken(refreshToken: string): Promise<ApiResponse<{ accessToken: string; refreshToken: string }>> {
const response = await api.post<ApiResponse<{ accessToken: string; refreshToken: string }>>(
`${this.basePath}/refresh`,
{ refreshToken }
);
return response.data;
}
async logout(): Promise<ApiResponse<MessageResponse>> {
const response = await api.post<ApiResponse<MessageResponse>>(`${this.basePath}/logout`);
return response.data;
}
// Helper to extract error message from API error
static getErrorMessage(error: unknown): string {
if (error instanceof AxiosError) {
const apiError = error.response?.data as ApiErrorResponse;
if (apiError?.message) {
return Array.isArray(apiError.message)
? apiError.message.join(', ')
: apiError.message;
}
}
if (error instanceof Error) {
return error.message;
}
return 'An unexpected error occurred';
}
// Helper to extract field errors
static getFieldErrors(error: unknown): Array<{ field: string; errors: string[] }> {
if (error instanceof AxiosError) {
const apiError = error.response?.data as ApiErrorResponse;
return apiError?.errors || [];
}
return [];
}
}
export const authService = new AuthService();
export { AuthService };

16
src/services/index.ts Normal file
View File

@@ -0,0 +1,16 @@
// API Client
export { default as api } from './api';
export type { ApiResponse, ApiErrorResponse } from './api';
// Services
export { authService, AuthService } from './auth.service';
export type {
RegisterRequest,
LoginRequest,
AuthUser,
AuthResponse,
ForgotPasswordRequest,
ResetPasswordRequest,
VerifyEmailRequest,
MessageResponse,
} from './auth.service';