All files / services api.ts

100% Statements 29/29
94.44% Branches 17/18
100% Functions 4/4
100% Lines 29/29

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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197                                                                                                  21x       21x       225x   225x 12x     225x                                   21x                   9x   9x                         21x 222x   222x 4x   4x   4x 2x                   2x 1x   1x       1x                     1x           1x   1x 1x     2x 2x     222x             21x                                                         21x  
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;
	}
});
 
// ============================================================================
// Unauthenticated Endpoints
// ============================================================================
 
/**
 * Endpoints that are reachable without a session.
 *
 * A 401 from one of these is a legitimate answer to the request — a bad
 * password, an expired reset token — not an expired session, so they must skip
 * the re-auth path below. With no refresh token to try, that path dispatches
 * `auth/logout`; the FSC-59 listener then resets the entire API cache, which
 * discards the mutation's own error before the form can render it. That is why
 * a failed login previously showed no message at all (FSC-162).
 */
const UNAUTHENTICATED_PATHS: readonly string[] = [
	'/auth/login',
	'/auth/register',
	'/auth/refresh',
	'/auth/forgot-password',
	'/auth/reset-password',
	'/auth/change-email/confirm'
];
 
function isUnauthenticatedRequest(args: string | FetchArgs): boolean {
	const url = typeof args === 'string' ? args : args.url;
 
	return UNAUTHENTICATED_PATHS.includes(url.split('?')[0]);
}
 
// ============================================================================
// 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 && !isUnauthenticatedRequest(args)) {
		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',
		'Configuration',
		'PaymentMethod',
		'UserManagement',
		'Document',
		'DocumentType',
		'InvestorUpload',
		'ProvidedDocument',
		'NotificationPreferences',
		'Consents',
		'CronJobs',
		'Disbursement',
		'SentEmail',
		'FundingRequest'
	],
	endpoints: () => ({})
});