40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import { UseQueryResult } from '@tanstack/react-query';
|
|
import { ApiError } from '@/lib/api/base/ApiError';
|
|
|
|
/**
|
|
* Converts React-Query error to ApiError for StateContainer compatibility
|
|
* This eliminates the need to repeat error conversion logic in every hook
|
|
*/
|
|
export function convertToApiError(error: any): ApiError | null {
|
|
if (!error) return null;
|
|
|
|
if (error instanceof ApiError) {
|
|
return error;
|
|
}
|
|
|
|
return new ApiError(
|
|
error.message || 'An unexpected error occurred',
|
|
'UNKNOWN_ERROR',
|
|
{ timestamp: new Date().toISOString() },
|
|
error instanceof Error ? error : undefined
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Helper function to enhance React-Query result with ApiError conversion
|
|
* Returns the same structure as before but with DRY error handling
|
|
*/
|
|
export function enhanceQueryResult<TData, TError = any>(
|
|
queryResult: UseQueryResult<TData, TError>
|
|
) {
|
|
const apiError = convertToApiError(queryResult.error);
|
|
|
|
return {
|
|
...queryResult,
|
|
error: apiError, // Directly return ApiError for StateContainer compatibility
|
|
retry: async () => {
|
|
await queryResult.refetch();
|
|
},
|
|
};
|
|
}
|