All files / services api.ts

100% Statements 26/26
92.85% Branches 13/14
100% Functions 3/3
100% Lines 26/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155                                                                                                  4x       4x       95x   95x 7x     95x                           4x 92x   92x 8x   8x   8x 2x                   2x 1x   1x       1x                     1x           1x   1x 1x     6x 6x     92x             4x                               4x  
import {
	type BaseQueryFn,
	createApi,
	type FetchArgs,
	fetchBaseQuery,
	type FetchBaseQueryError,
	type FetchBaseQueryMeta
} from '@reduxjs/toolkit/query/react';
 
import type {RootState} from '../store/store';
import {logger} from '../utils/logger';
 
// ============================================================================
// Types
// ============================================================================
 
interface RefreshApiResponse {
	success: boolean;
	message: string;
	data: {
		user: {
			userId: number;
			username: string;
			email: string;
			role: string;
		};
		accessToken: string;
		refreshToken: string;
		tokenType: string;
		expiresIn: number;
	};
}
 
interface SetCredentialsPayload {
	user: {
		userId: number;
		username: string;
		email: string;
		role: string;
	};
	accessToken: string;
	refreshToken: string;
}
 
// ============================================================================
// Base Query Configuration
// ============================================================================
 
const API_BASE_URL: string =
	typeof import.meta.env.VITE_API_URL === 'string'
		? import.meta.env.VITE_API_URL
		: '/api';
 
const baseQuery = fetchBaseQuery({
	baseUrl: API_BASE_URL,
	prepareHeaders: (headers, {getState}) => {
		// Get token from Redux store
		const token = (getState() as RootState).auth.accessToken;
 
		if (token !== null && token !== '') {
			headers.set('Authorization', `Bearer ${token}`);
		}
 
		return headers;
	}
});
 
// ============================================================================
// Re-auth Query Wrapper
// ============================================================================
 
const baseQueryWithReAuth: BaseQueryFn<
	string | FetchArgs,
	unknown,
	FetchBaseQueryError,
	object,
	FetchBaseQueryMeta
> = async (args, api, extraOptions) => {
	let result = await baseQuery(args, api, extraOptions);
 
	if (result.error?.status === 401) {
		logger.debug('Received 401, attempting token refresh');
 
		const refreshToken = (api.getState() as RootState).auth.refreshToken;
 
		if (refreshToken !== null && refreshToken !== '') {
			const refreshResult = await baseQuery(
				{
					url: '/auth/refresh',
					method: 'POST',
					body: {refreshToken}
				},
				api,
				extraOptions
			);
 
			if (refreshResult.data !== undefined) {
				const responseData = refreshResult.data as RefreshApiResponse;
 
				logger.debug('Token refresh successful', {
					userId: responseData.data.user.userId
				});
 
				const payload: SetCredentialsPayload = {
					user: {
						userId: responseData.data.user.userId,
						username: responseData.data.user.username,
						email: responseData.data.user.email,
						role: responseData.data.user.role
					},
					accessToken: responseData.data.accessToken,
					refreshToken: responseData.data.refreshToken
				};
 
				api.dispatch({
					type: 'auth/setCredentials',
					payload
				});
 
				// Retry the initial query with new token
				result = await baseQuery(args, api, extraOptions);
			} else {
				logger.warn('No refresh failed, logging out');
				api.dispatch({type: 'auth/logout'});
			}
		} else {
			logger.debug('No refresh token available, logging out');
			api.dispatch({type: 'auth/logout'});
		}
	}
	return result;
};
 
// ============================================================================
// API Definition
// ============================================================================
 
export const api = createApi({
	reducerPath: 'api',
	baseQuery: baseQueryWithReAuth,
	tagTypes: [
		'User',
		'Investor',
		'Account',
		'AccountSummary',
		'Transaction',
		'AdminStats',
		'AdminInvestors',
		'SuperAdminAccounts',
		'ErrorLog',
		'SystemSettings',
		'Loan'
	],
	endpoints: () => ({})
});