@phygitallabs/statistics
v6.1.0
Published
A comprehensive statistics package that provides React hooks for analytics data, built on top of OpenAPI-generated services and React Query.
Readme
Statistics Package
A comprehensive statistics package that provides React hooks for analytics data, built on top of OpenAPI-generated services and React Query.
Features
- 🚀 Auto-generated hooks from OpenAPI specification
- 🔧 Configurable API client with authentication support
- ⚡ React Query integration with optimized caching
- 🔄 Dynamic configuration updates without page reload
- 🛡️ TypeScript support with full type safety
- 📊 Comprehensive analytics endpoints for various statistics
Installation
npm install statistics
# or
yarn add statisticsQuick Start
1. Basic Setup
import { StatisticsProvider } from 'statistics';
function App() {
const config = {
baseUrl: 'https://api.statistics.example.com',
apiKey: 'your-api-key',
};
return (
<StatisticsProvider config={config}>
<YourAppComponents />
</StatisticsProvider>
);
}2. Advanced Setup with Token Refresh (Similar to QueryProvider)
import { StatisticsProvider, type StatisticsConfig } from 'statistics';
const memoizedRefreshToken = async () => {
const refreshToken = localStorage.getItem('refreshToken');
const response = await fetch('/api/auth/refresh', {
method: 'POST',
body: JSON.stringify({ refreshToken }),
});
return response.json();
};
function App() {
const config: StatisticsConfig = {
baseUrl: 'https://api.statistics.com/v1',
accessTokenKey: 'accessToken',
refreshTokenKey: 'refreshToken',
httpMaxRetries: 3,
onTokenRefresh: memoizedRefreshToken,
onAuthError: () => window.location.href = '/login',
};
const queryClientConfig = {
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 5,
},
},
};
const responseInterceptors = {
onFulfilled: (response) => response,
onRejected: async (error) => {
// Auto token refresh logic
// ... (handled automatically by provider)
return Promise.reject(error);
},
};
return (
<StatisticsProvider
config={config}
queryClientConfig={queryClientConfig}
responseInterceptors={responseInterceptors}
>
<YourAppComponents />
</StatisticsProvider>
);
}3. Use statistics hooks in your components
import { useV1AnalyticsServiceGetV1AnalyticsActiveChipCount } from 'statistics';
function Dashboard() {
const { data, isLoading, error } = useV1AnalyticsServiceGetV1AnalyticsActiveChipCount({
organizationId: 'org-123',
projectId: 'project-456',
startDate: '2024-01-01',
endDate: '2024-12-31',
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>Active Chips: {data?.data?.total}</div>;
}Configuration
StatisticsConfig Options
interface StatisticsConfig {
baseUrl: string; // Required: API base URL
apiKey?: string; // Optional: API key for authentication
token?: string; // Optional: Bearer token for authentication
headers?: Record<string, string>; // Optional: Additional headers
withCredentials?: boolean; // Optional: Include credentials (default: false)
credentials?: 'include' | 'omit' | 'same-origin'; // Optional: Credentials mode
// Advanced token management
accessTokenKey?: string; // Optional: Storage key for access token (default: 'accessToken')
refreshTokenKey?: string; // Optional: Storage key for refresh token (default: 'refreshToken')
userInfoKey?: string; // Optional: Storage key for user info (default: 'userInfo')
retryAttemptsKey?: string; // Optional: Storage key for retry attempts (default: 'retryAttemptsRefreshToken')
httpMaxRetries?: number; // Optional: Max retry attempts (default: 3)
// Token refresh callback
onTokenRefresh?: () => Promise<{ accessToken: string; refreshToken: string } | null>;
onAuthError?: () => void; // Optional: Called when auth fails
// Custom storage functions (default: localStorage)
getFromStorage?: (key: string) => string | null;
setToStorage?: (key: string, value: string) => void;
removeFromStorage?: (key: string) => void;
}Authentication Methods
API Key Authentication
const config = {
baseUrl: 'https://api.statistics.example.com',
apiKey: 'your-api-key',
};Bearer Token Authentication
const config = {
baseUrl: 'https://api.statistics.example.com',
token: 'your-bearer-token',
};Custom Headers
const config = {
baseUrl: 'https://api.statistics.example.com',
headers: {
'Authorization': 'Custom your-token',
'X-Custom-Header': 'value',
},
};Available Hooks
Provider Hooks
useStatisticsConfig- Get full provider contextuseStatisticsApiConfig- Get current API configurationuseUpdateStatisticsConfig- Update configuration dynamicallyuseStatisticsQueryClient- Get React Query client instanceuseStatisticsToken- Get current access token from storageuseStatisticsRefreshToken- Manually refresh tokenuseStatisticsClearAuth- Clear all authentication data
Analytics Hooks
useV1AnalyticsServiceGetV1AnalyticsActiveChipCount- Get active chip countuseV1AnalyticsServiceGetV1AnalyticsChipCount- Get chip count with filtersuseV1AnalyticsServiceGetV1AnalyticsUserCount- Get user count statisticsuseV1AnalyticsServiceGetV1AnalyticsScanCount- Get scan count analyticsuseV1AnalyticsServiceGetV1AnalyticsLeadCount- Get lead count statistics
Project Hooks
useV1ProjectsServiceGetV1ProjectsStatistics- Get project statisticsuseV1ProjectsServiceGetV1ProjectsByProjectIdItemStatistics- Get item statistics for a project
Campaign Hooks
useV1CampaignsServiceGetV1CampaignsByCampaignIdLocationsStatisticsCheckIn- Get location check-in statisticsuseV1CampaignsServiceGetV1CampaignsByCampaignIdRankingUserCheckIn- Get user ranking statistics
Reward Hooks
useV1AdminUserRewardsServiceGetV1AdminUserRewardsStatistic- Get user reward statisticsuseV1RewardModelsServiceGetV1ProjectsByProjectIdRewardModelsStatistics- Get reward model statistics
Advanced Usage
Dynamic Configuration Updates
import { useUpdateStatisticsConfig, useStatisticsApiConfig } from 'statistics';
function ConfigComponent() {
const config = useStatisticsApiConfig();
const updateConfig = useUpdateStatisticsConfig();
const switchEnvironment = () => {
updateConfig({
baseUrl: 'https://staging-api.statistics.example.com',
apiKey: 'staging-api-key',
});
};
return (
<div>
<p>Current API: {config.baseUrl}</p>
<button onClick={switchEnvironment}>Switch to Staging</button>
</div>
);
}Custom Query Client
import { QueryClient } from '@tanstack/react-query';
import { StatisticsProvider } from 'statistics';
const customQueryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 10, // 10 minutes
gcTime: 1000 * 60 * 60, // 1 hour
retry: 3,
refetchOnWindowFocus: false,
},
},
});
function App() {
return (
<StatisticsProvider
config={config}
queryClient={customQueryClient}
>
<YourApp />
</StatisticsProvider>
);
}Error Handling
function StatisticsComponent() {
const {
data,
isLoading,
error,
refetch,
failureCount,
isError
} = useV1AnalyticsServiceGetV1AnalyticsActiveChipCount({
organizationId: 'org-123',
});
if (isLoading) return <div>Loading...</div>;
if (isError) {
return (
<div className="error-state">
<p>Failed to load data (Attempt {failureCount})</p>
<p>Error: {error?.message}</p>
<button onClick={() => refetch()}>Retry</button>
</div>
);
}
return <div>Data: {JSON.stringify(data)}</div>;
}Environment Variables
You can use environment variables for configuration:
const config = {
baseUrl: process.env.NEXT_PUBLIC_STATISTICS_API_URL || 'https://api.statistics.example.com',
apiKey: process.env.STATISTICS_API_KEY,
};TypeScript Support
The package provides full TypeScript support with auto-generated types:
import type {
StatisticsConfig,
V1AnalyticsServiceGetV1AnalyticsActiveChipCountDefaultResponse
} from 'statistics';
function TypedComponent() {
const { data }: { data?: V1AnalyticsServiceGetV1AnalyticsActiveChipCountDefaultResponse } =
useV1AnalyticsServiceGetV1AnalyticsActiveChipCount();
// data is fully typed
const total = data?.data?.total;
}Development
Regenerating API Hooks
When the OpenAPI specification is updated:
npm run codegenThis will regenerate all hooks and types from the statistic.yaml file.
License
ISC
