feat: Implement a structured API service layer for authentication and user management, replacing the old API utility.
This commit is contained in:
120
src/services/api.ts
Normal file
120
src/services/api.ts
Normal file
@@ -0,0 +1,120 @@
|
||||
import axios, { AxiosError, AxiosInstance, InternalAxiosRequestConfig } from 'axios';
|
||||
|
||||
// API Response types
|
||||
export interface ApiResponse<T = unknown> {
|
||||
success: boolean;
|
||||
data: T;
|
||||
statusCode?: number;
|
||||
timestamp?: string;
|
||||
message?: 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;
|
||||
},
|
||||
async (error: AxiosError<ApiErrorResponse>) => {
|
||||
const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean };
|
||||
|
||||
// Handle 401 Unauthorized - try to refresh token
|
||||
if (error.response?.status === 401 && !originalRequest._retry) {
|
||||
originalRequest._retry = true;
|
||||
|
||||
try {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (refreshToken) {
|
||||
const response = await axios.post(
|
||||
`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api/v1'}/auth/refresh`,
|
||||
{ refreshToken }
|
||||
);
|
||||
|
||||
const { accessToken, refreshToken: newRefreshToken } = response.data.data;
|
||||
localStorage.setItem('accessToken', accessToken);
|
||||
localStorage.setItem('refreshToken', newRefreshToken);
|
||||
|
||||
// Retry original request with new token
|
||||
if (originalRequest.headers) {
|
||||
originalRequest.headers.Authorization = `Bearer ${accessToken}`;
|
||||
}
|
||||
return api(originalRequest);
|
||||
}
|
||||
} catch (refreshError) {
|
||||
// Refresh failed, clear storage and redirect to login
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
// Helper to extract error message
|
||||
export function 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
|
||||
export function getFieldErrors(error: unknown): Array<{ field: string; errors: string[] }> {
|
||||
if (error instanceof AxiosError) {
|
||||
const apiError = error.response?.data as ApiErrorResponse;
|
||||
return apiError?.errors || [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export default api;
|
||||
115
src/services/auth.service.ts
Normal file
115
src/services/auth.service.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import api, { ApiResponse } from './api';
|
||||
|
||||
// Types
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
user: AuthUser;
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
}
|
||||
|
||||
export interface MessageResponse {
|
||||
message: string;
|
||||
}
|
||||
|
||||
// Auth Service
|
||||
class AuthService {
|
||||
private basePath = '/auth';
|
||||
|
||||
async login(data: LoginRequest): Promise<AuthResponse> {
|
||||
const response = await api.post<ApiResponse<AuthResponse>>(
|
||||
`${this.basePath}/login`,
|
||||
data
|
||||
);
|
||||
|
||||
const authData = response.data.data;
|
||||
|
||||
// Check if user is ADMIN
|
||||
if (authData.user.role !== 'ADMIN') {
|
||||
throw new Error('Access denied. Admin privileges required.');
|
||||
}
|
||||
|
||||
// Store tokens and user
|
||||
localStorage.setItem('accessToken', authData.accessToken);
|
||||
localStorage.setItem('refreshToken', authData.refreshToken);
|
||||
localStorage.setItem('user', JSON.stringify(authData.user));
|
||||
|
||||
return authData;
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
try {
|
||||
await api.post<ApiResponse<MessageResponse>>(`${this.basePath}/logout`);
|
||||
} finally {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
}
|
||||
|
||||
async getCurrentUser(): Promise<AuthUser> {
|
||||
const response = await api.get<ApiResponse<AuthUser>>(`${this.basePath}/me`);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async refreshToken(): Promise<{ accessToken: string; refreshToken: string }> {
|
||||
const refreshToken = localStorage.getItem('refreshToken');
|
||||
if (!refreshToken) {
|
||||
throw new Error('No refresh token available');
|
||||
}
|
||||
|
||||
const response = await api.post<ApiResponse<{ accessToken: string; refreshToken: string }>>(
|
||||
`${this.basePath}/refresh`,
|
||||
{ refreshToken }
|
||||
);
|
||||
|
||||
const tokens = response.data.data;
|
||||
localStorage.setItem('accessToken', tokens.accessToken);
|
||||
localStorage.setItem('refreshToken', tokens.refreshToken);
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
// Get stored user from localStorage
|
||||
getStoredUser(): AuthUser | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
|
||||
const storedUser = localStorage.getItem('user');
|
||||
if (storedUser) {
|
||||
try {
|
||||
return JSON.parse(storedUser);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Check if user is authenticated
|
||||
isAuthenticated(): boolean {
|
||||
if (typeof window === 'undefined') return false;
|
||||
return !!localStorage.getItem('accessToken');
|
||||
}
|
||||
|
||||
// Clear auth data
|
||||
clearAuth(): void {
|
||||
localStorage.removeItem('accessToken');
|
||||
localStorage.removeItem('refreshToken');
|
||||
localStorage.removeItem('user');
|
||||
}
|
||||
}
|
||||
|
||||
export const authService = new AuthService();
|
||||
21
src/services/index.ts
Normal file
21
src/services/index.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
// API Client
|
||||
export { default as api } from './api';
|
||||
export type { ApiResponse, ApiErrorResponse } from './api';
|
||||
export { getErrorMessage, getFieldErrors } from './api';
|
||||
|
||||
// Auth Service
|
||||
export { authService } from './auth.service';
|
||||
export type {
|
||||
LoginRequest,
|
||||
AuthUser,
|
||||
AuthResponse,
|
||||
MessageResponse,
|
||||
} from './auth.service';
|
||||
|
||||
// Users Service
|
||||
export { usersService } from './users.service';
|
||||
export type {
|
||||
User,
|
||||
UsersListResponse,
|
||||
UserFilters,
|
||||
} from './users.service';
|
||||
79
src/services/users.service.ts
Normal file
79
src/services/users.service.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import api, { ApiResponse } from './api';
|
||||
|
||||
// Types
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
role: string;
|
||||
status: string;
|
||||
emailVerified: boolean;
|
||||
authProvider: string;
|
||||
createdAt: string;
|
||||
lastLoginAt: string | null;
|
||||
profile: {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
avatar: string | null;
|
||||
phone: string | null;
|
||||
city: string | null;
|
||||
state: string | null;
|
||||
country: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export interface UsersListResponse {
|
||||
users: User[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface UserFilters {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
role?: string;
|
||||
status?: string;
|
||||
search?: string;
|
||||
}
|
||||
|
||||
// Users Service
|
||||
class UsersService {
|
||||
private basePath = '/users';
|
||||
|
||||
async getUsers(filters: UserFilters = {}): Promise<UsersListResponse> {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (filters.page) params.append('page', filters.page.toString());
|
||||
if (filters.limit) params.append('limit', filters.limit.toString());
|
||||
if (filters.role) params.append('role', filters.role);
|
||||
if (filters.status) params.append('status', filters.status);
|
||||
if (filters.search) params.append('search', filters.search);
|
||||
|
||||
const queryString = params.toString();
|
||||
const url = queryString ? `${this.basePath}?${queryString}` : this.basePath;
|
||||
|
||||
const response = await api.get<ApiResponse<UsersListResponse>>(url);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async getUserById(id: string): Promise<User> {
|
||||
const response = await api.get<ApiResponse<User>>(`${this.basePath}/${id}`);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async updateUser(id: string, data: Partial<User>): Promise<User> {
|
||||
const response = await api.patch<ApiResponse<User>>(`${this.basePath}/${id}`, data);
|
||||
return response.data.data;
|
||||
}
|
||||
|
||||
async deleteUser(id: string): Promise<void> {
|
||||
await api.delete(`${this.basePath}/${id}`);
|
||||
}
|
||||
|
||||
async updateUserStatus(id: string, status: string): Promise<User> {
|
||||
const response = await api.patch<ApiResponse<User>>(`${this.basePath}/${id}/status`, { status });
|
||||
return response.data.data;
|
||||
}
|
||||
}
|
||||
|
||||
export const usersService = new UsersService();
|
||||
Reference in New Issue
Block a user