@footballbingo/client
v2.7.0
Published
Auto-generated TypeScript client for the Football Bingo API
Maintainers
Readme
@football-bingo/client
Auto-generated TypeScript client for the Football Bingo API
Features
✅ 100% API Coverage - Generated directly from OpenAPI specification ✅ Fully Typed - Complete TypeScript support with IntelliSense ✅ Auto-Generated - Stays in sync with API changes ✅ Promise-based - Modern async/await support ✅ Tree-shakeable - Import only what you need ✅ Zero Dependencies - Uses native fetch API
Installation
npm install @football-bingo/clientQuick Start
import { createClient } from '@football-bingo/client';
// Initialize the client
const client = createClient({
BASE: 'https://api.footballbingo.com',
TOKEN: async () => {
// Return your auth token (from Clerk, Auth0, etc.)
return await getAuthToken();
},
});
// Use the client
const user = await client.users.getUsersMe();
const fixtures = await client.contentFixtures.getContentFixtures({
status: 'live',
limit: 20,
});Configuration
Basic Configuration
const client = createClient({
BASE: 'https://api.footballbingo.com', // API base URL
VERSION: '1.0.0', // API version
TOKEN: async () => string, // Auth token provider
USERNAME: 'user', // Basic auth username
PASSWORD: 'pass', // Basic auth password
HEADERS: {}, // Additional headers
ENCODE_PATH: (path) => path, // Custom path encoding
});With Clerk Authentication
import { useAuth } from '@clerk/clerk-react';
import { createClient } from '@football-bingo/client';
function useFootballBingoClient() {
const { getToken } = useAuth();
return createClient({
BASE: process.env.REACT_APP_API_URL!,
TOKEN: () => getToken(),
});
}With Auth0
import { useAuth0 } from '@auth0/auth0-react';
import { createClient } from '@football-bingo/client';
function useFootballBingoClient() {
const { getAccessTokenSilently } = useAuth0();
return createClient({
BASE: process.env.REACT_APP_API_URL!,
TOKEN: () => getAccessTokenSilently(),
});
}API Services
The client provides access to 40 service modules covering all API endpoints:
Core Services
- users - User management and profiles
- predictor - Match predictions and stats
- contentFixtures - Football match fixtures
- bingo - Bingo game management
- wallet - User wallet and transactions
- store - In-app purchases and inventory
- leaderboards - Global and category leaderboards
Content Services
- contentCountries - Countries data
- contentLeagues - League information
- contentTeams - Team data and stats
- contentPlayers - Player profiles and statistics
- contentNews - Football news articles
- contentOdds - Betting odds and markets
- contentStandings - League standings
- contentStatistics - Match and player stats
- contentTransfers - Transfer news and history
- contentTrophies - Trophy and honors data
Community Services
- communityLineups - Share and browse lineups
- communityTacticsBoards - Tactical analysis boards
- communityTransferPlans - Transfer planning tool
- communitySharedGames - Share bingo games
- communityChallenges - Community challenges
- communityGameChat - In-game chat
Game Services
- bingo - Bingo game creation and management
- bingoGames - Active games and sessions
- bingoBoards - Player boards and tiles
- bingoParticipations - Game participation
- eventPools - Event pool management
- sponsors - Sponsor management
Progression Services
- achievements - Achievement system
- challenges - Daily and weekly challenges
- progression - User progression and XP
- activities - User activity tracking
AI & Support Services
- aiChat - AI pundit conversations
- notifications - Push notifications
- admin - Admin operations (requires admin role)
Usage Examples
Get Current User
const user = await client.users.getUsersMe();
console.log(`Welcome ${user.username}!`);
console.log(`Level: ${user.level}, Coins: ${user.coins}`);Create a Prediction
const prediction = await client.predictor.postPredictions({
requestBody: {
fixtureId: 'fixture-123',
homeScore: 2,
awayScore: 1,
result: 'home',
confidence: 4,
},
});
console.log('Prediction created:', prediction.id);Get Live Fixtures
const liveFixtures = await client.contentFixtures.getContentFixtures({
status: 'live',
limit: 10,
});
liveFixtures.data.forEach(fixture => {
console.log(`${fixture.homeTeam.name} vs ${fixture.awayTeam.name}`);
console.log(`Score: ${fixture.goals.home}-${fixture.goals.away}`);
});Join a Bingo Game
const game = await client.bingo.postBingoGames({
requestBody: {
fixtureId: 'fixture-123',
isPublic: true,
entryFee: 100,
},
});
console.log(`Game created! Session code: ${game.sessionCode}`);Get Leaderboard
const leaderboard = await client.leaderboards.getLeaderboards({
category: 'predictions',
period: 'week',
});
leaderboard.entries.forEach((entry, index) => {
console.log(`${index + 1}. ${entry.username} - ${entry.score} points`);
});Purchase Store Item
const purchase = await client.monetization.postStoreItemsItemIdPurchaseWithCoins({
itemId: 'item-uuid',
requestBody: { quantity: 1 },
});
console.log('Purchase successful!');
console.log('New balance:', purchase.newBalance.coins);Get Wallet Balance
const balance = await client.wallet.getWallet();
console.log(`Coins: ${balance.coins}`);
console.log(`XP: ${balance.xp}`);
console.log(`Level: ${balance.level}`);Error Handling
import { ApiError } from '@football-bingo/client';
try {
await client.predictor.postPredictions({
requestBody: predictionData,
});
} catch (error) {
if (error instanceof ApiError) {
console.error('API Error:', error.status, error.body);
// Handle specific error codes
if (error.status === 400) {
console.error('Validation error:', error.body.error.message);
} else if (error.status === 401) {
// Redirect to login
window.location.href = '/login';
}
} else {
console.error('Unknown error:', error);
}
}React Integration
Custom Hook
import { useMemo } from 'react';
import { useAuth } from '@clerk/clerk-react';
import { createClient } from '@football-bingo/client';
export function useFootballBingoClient() {
const { getToken } = useAuth();
return useMemo(
() =>
createClient({
BASE: process.env.REACT_APP_API_URL!,
TOKEN: () => getToken(),
}),
[getToken]
);
}With React Query
import { useQuery } from '@tanstack/react-query';
import { useFootballBingoClient } from './useFootballBingoClient';
function useUser() {
const client = useFootballBingoClient();
return useQuery({
queryKey: ['user'],
queryFn: () => client.users.getUsersMe(),
});
}
function useLiveFixtures() {
const client = useFootballBingoClient();
return useQuery({
queryKey: ['fixtures', 'live'],
queryFn: () => client.contentFixtures.getContentFixtures({ status: 'live' }),
refetchInterval: 30000, // Refetch every 30s
});
}Component Example
function PredictionsPage() {
const client = useFootballBingoClient();
const [predictions, setPredictions] = useState([]);
useEffect(() => {
async function loadPredictions() {
const result = await client.predictor.getPredictions();
setPredictions(result.data);
}
loadPredictions();
}, [client]);
return (
<div>
{predictions.map(prediction => (
<PredictionCard key={prediction.id} prediction={prediction} />
))}
</div>
);
}Advanced Usage
Custom Request Configuration
// Set global headers
client.request.config.HEADERS = {
'X-Custom-Header': 'value',
};
// Update base URL at runtime
client.request.config.BASE = 'https://api-staging.footballbingo.com';
// Update auth token
client.request.config.TOKEN = async () => newGetTokenFunction();Canceling Requests
import { CancelablePromise } from '@football-bingo/client';
const request: CancelablePromise<any> = client.contentFixtures.getContentFixtures();
// Cancel the request
request.cancel();TypeScript Support
All types are automatically inferred:
import type {
UserProfileDTO,
PredictionDTO,
FixtureDTO
} from '@football-bingo/client';
const user: UserProfileDTO = await client.users.getUsersMe();
const predictions: PredictionDTO[] = (await client.predictor.getPredictions()).data;
const fixture: FixtureDetailDTO = await client.contentFixtures.getContentFixturesId({ id: 123 });Regenerating the Client
If the API changes, regenerate the client:
cd sdk
npm run generate
npm run buildThis will:
- Export the latest OpenAPI spec from the backend
- Generate fresh TypeScript client code
- Compile to JavaScript
Best Practices
- Create client instance once - Initialize at app root
- Use React Query - Combine with React Query for caching and state management
- Handle errors globally - Set up global error handling
- Type everything - Leverage TypeScript for compile-time safety
- Keep token fresh - Ensure
TOKENfunction returns valid tokens
API Documentation
Full API documentation is available at:
- Development: http://localhost:3004/docs
- Production: https://api.footballbingo.com/docs
Support
- Issues: GitHub Issues
- Docs: API Documentation
License
ISC
