pagamio-frontend-commons-lib
Version:
Pagamio library for Frontend reusable components like the form engine and table container
106 lines (105 loc) • 3.25 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
/**
* @fileoverview API Context and utilities for managing a shared API client instance
* Provides context, provider component, and hooks for consistent API access across the application
*/
import { createContext, useContext, useMemo } from 'react';
import { ApiClient } from './client';
/**
* React context for sharing the API client instance
* Initialized as undefined to ensure proper provider wrapping
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
const ApiContext = createContext(undefined);
/**
* Provider component for the API context
* Makes the API client instance available to all child components
*
* @template T - Type extending CustomAuthConfig
*
* @example
* ```tsx
* function App() {
* return (
* <ApiProvider apiClient={apiClient}>
* <MyComponents />
* </ApiProvider>
* );
* }
* ```
*/
export function ApiProvider({ children, apiClient, mocked = false, mockConfig = [], }) {
// Set mock config on the API client if mocking is enabled
if (mocked) {
apiClient.setMockConfig(mockConfig);
}
const value = useMemo(() => ({ apiClient }), [apiClient]);
return _jsx(ApiContext.Provider, { value: value, children: children });
}
/**
* Hook for accessing the API client instance
* Must be used within an ApiProvider component
*
* @template T - Type extending CustomAuthConfig for type-safe API operations
* @returns The shared API client instance
* @throws Error if used outside of ApiProvider
*
* @example
* ```tsx
* function MyComponent() {
* const api = useApi<MyAuthConfig>();
*
* const fetchData = async () => {
* try {
* const data = await api.get('/endpoint');
* // Handle response
* } catch (error) {
* // Handle error
* }
* };
*
* return <div>...</div>;
* }
* ```
*/
export function useApi() {
const context = useContext(ApiContext);
if (!context) {
throw new Error('useApi must be used within an ApiProvider');
}
return context.apiClient;
}
/**
* Factory function to create a configured ApiClient instance
*
* @template T - Type extending CustomAuthConfig that defines the shape of authentication data
* @param config - Configuration options for the API client
* @param config.baseURL - Base URL for all API requests
* @param config.tokenManager - Token manager instance for handling authentication
* @param config.defaultHeaders - Default headers to include in all requests
* @param config.timeout - Request timeout in milliseconds (default: 30000)
* @param config.retries - Number of retry attempts for failed requests (default: 1)
* @returns Configured ApiClient instance
*
* @example
* ```typescript
* const apiClient = createApiClient<MyAuthConfig>({
* baseURL: 'https://api.example.com',
* tokenManager: tokenManager,
* defaultHeaders: {
* 'Content-Type': 'application/json',
* },
* timeout: 5000,
* retries: 2,
* });
* ```
*/
export function createApiClient({ baseURL, tokenManager, defaultHeaders = {}, timeout = 30000, retries = 1, }) {
return new ApiClient({
baseURL,
tokenManager,
defaultHeaders,
timeout,
retries,
});
}