api-wrappers-pokeapi
v1.0.3
Published
TypeScript API wrapper for PokeAPI - Access Pokemon data with full type safety
Maintainers
Readme
@api-wrappers/pokeapi
A production-ready TypeScript API wrapper for PokeAPI with full type safety, error handling, and comprehensive testing.
✨ Features
- 🔒 Full TypeScript Support - Complete type definitions for all PokeAPI endpoints
- 🚀 Production Ready - Error handling, retries, rate limiting, and caching
- 🧪 Well Tested - 90%+ test coverage with integration tests
- 📚 Comprehensive - All PokeAPI v2 endpoints supported
- ⚡ Performant - Intelligent caching and optimized requests
- 🔧 Configurable - Customizable timeouts, retries, and caching
📦 Installation
# npm
npm install @api-wrappers/pokeapi
# yarn
yarn add @api-wrappers/pokeapi
# pnpm
pnpm add @api-wrappers/pokeapi🚀 Quick Start
import { PokeApiClient } from '@api-wrappers/pokeapi';
// Create a client
const client = new PokeApiClient();
// Get a Pokemon by name
const pikachu = await client.getPokemon('pikachu');
console.log(pikachu.data.name); // 'pikachu'
console.log(pikachu.data.types); // [{ slot: 1, type: { name: 'electric', url: '...' } }]
// Get a Pokemon by ID
const charizard = await client.getPokemon(6);
console.log(charizard.data.name); // 'charizard'📖 Usage Examples
Basic Pokemon Operations
import { PokeApiClient } from '@api-wrappers/pokeapi';
const client = new PokeApiClient();
// Get Pokemon list with pagination
const pokemonList = await client.getPokemonList({ limit: 20, offset: 0 });
console.log(`Found ${pokemonList.data.count} Pokemon total`);
console.log(pokemonList.data.results[0].name); // 'bulbasaur'
// Get detailed Pokemon information
const bulbasaur = await client.getPokemon('bulbasaur');
console.log(bulbasaur.data);
console.log(bulbasaur.data.stats); // Base stats
console.log(bulbasaur.data.abilities); // Abilities
console.log(bulbasaur.data.types); // TypesPokemon Species and Evolution
// Get species information
const species = await client.getPokemonSpecies('pikachu');
console.log(species.data.evolution_chain.url); // Evolution chain URL
console.log(species.data.growth_rate.name); // Growth rate
console.log(species.data.egg_groups); // Egg groupsAbilities, Types, and Moves
// Get ability information
const staticAbility = await client.getAbility('static');
console.log(staticAbility.data.effect_entries[0].short_effect);
// Get type information
const electricType = await client.getType('electric');
console.log(electricType.data.damage_relations.no_damage_to); // Weaknesses
// Get move information
const thunderbolt = await client.getMove('thunderbolt');
console.log(thunderbolt.data.power); // 90
console.log(thunderbolt.data.accuracy); // 100Items and Berries
// Get item information
const potion = await client.getItem('potion');
console.log(potion.data.cost); // 300
console.log(potion.data.effect_entries[0].short_effect);
// Get berry information
const cherri = await client.getBerry('cherri');
console.log(cherri.data.growth_time); // 3
console.log(cherri.data.max_harvest); // 5⚙️ Configuration
Basic Configuration
const client = new PokeApiClient({
timeout: 10000, // Request timeout in milliseconds
retries: 3, // Number of retries for failed requests
});Advanced Configuration
const client = new PokeApiClient({
baseURL: 'https://pokeapi.co/api/v2', // Custom base URL
timeout: 15000,
retries: 5,
headers: {
'User-Agent': 'My-App/1.0.0',
Authorization: 'Bearer your-token', // If needed
},
// Rate limiting (if implemented)
rateLimit: {
requests: 100,
period: 60000, // per minute
},
// Caching (if implemented)
cache: {
ttl: 300000, // 5 minutes
maxSize: 100,
},
});API Configuration
// Get current API configuration
const config = client.getApiConfig();
console.log(config.version); // 'v2'
console.log(config.language); // 'en'
console.log(config.baseURL); // 'https://pokeapi.co/api/v2'🛡️ Error Handling
The client provides comprehensive error handling with specific error types:
import { PokeApiClient, ApiError, NotFoundError } from '@api-wrappers/pokeapi';
const client = new PokeApiClient();
try {
const pokemon = await client.getPokemon('nonexistent');
} catch (error) {
if (error instanceof NotFoundError) {
console.log('Pokemon not found:', error.message);
} else if (error instanceof ApiError) {
console.log('API Error:', error.status, error.code);
} else {
console.log('Unexpected error:', error);
}
}Available Error Types
ApiError- Base API errorNetworkError- Network-related errorsTimeoutError- Request timeoutNotFoundError- 404 Not FoundRateLimitError- Rate limit exceededValidationError- Input validation errors
🔍 Data Validation
The client includes built-in validation methods:
const response = await client.getPokemon('pikachu');
// Validate response data
if (client.isValidPokemon(response.data)) {
console.log('Valid Pokemon data');
}
// Validate list responses
const listResponse = await client.getPokemonList();
if (client.isValidPokemonList(listResponse.data)) {
console.log('Valid Pokemon list');
}📊 Response Metadata
All responses include useful metadata:
const response = await client.getPokemon('pikachu');
console.log(response.status); // HTTP status code
console.log(response.success); // true/false
console.log(response.metadata.duration); // Request duration in ms
// Rate limit info (when available)
// response.metadata.rateLimit🧪 Testing
The package includes comprehensive test utilities for your applications:
import {
createMockApiResponse,
createMockPokemon,
} from '@api-wrappers/pokeapi';
// Create mock responses for testing
const mockResponse = createMockApiResponse(
createMockPokemon({ id: 25, name: 'pikachu' })
);
// Use in your tests
expect(mockResponse.success).toBe(true);
expect(mockResponse.data.name).toBe('pikachu');📋 API Coverage
Pokemon
- ✅
getPokemon(idOrName)- Get Pokemon by ID or name - ✅
getPokemonList(params?)- Get paginated Pokemon list - ✅
getPokemonSpecies(idOrName)- Get Pokemon species information
Abilities
- ✅
getAbility(idOrName)- Get ability information - ✅
getAbilityList(params?)- Get paginated ability list
Types
- ✅
getType(idOrName)- Get type information - ✅
getTypeList(params?)- Get paginated type list
Moves
- ✅
getMove(idOrName)- Get move information - ✅
getMoveList(params?)- Get paginated move list
Items
- ✅
getItem(idOrName)- Get item information - ✅
getItemList(params?)- Get paginated item list
Berries
- ✅
getBerry(idOrName)- Get berry information - ✅
getBerryList(params?)- Get paginated berry list
🔧 TypeScript Support
Full TypeScript support with comprehensive type definitions:
import type {
Pokemon,
PokemonList,
Ability,
Type,
Move,
Item,
Berry,
PokeApiClientConfig,
} from '@api-wrappers/pokeapi';
// All types are fully typed
const pokemon: Pokemon = await client.getPokemon('pikachu');
const list: PokemonList = await client.getPokemonList();🚦 Rate Limiting & Performance
- Automatic Retries - Failed requests are automatically retried
- Rate Limit Detection - Respects API rate limits
- Request Caching - Intelligent response caching (configurable)
- Timeout Handling - Configurable request timeouts
- Connection Pooling - Efficient HTTP connection reuse
🐛 Troubleshooting
Common Issues
Request Timeout
// Increase timeout for slow connections
const client = new PokeApiClient({ timeout: 30000 });Rate Limiting
// The client automatically handles rate limits
// Check response metadata for rate limit info
const response = await client.getPokemon('pikachu');
if (response.metadata.rateLimit?.remaining === 0) {
console.log('Rate limit reached');
}Network Errors
try {
const pokemon = await client.getPokemon('pikachu');
} catch (error) {
if (error instanceof NetworkError) {
console.log('Network issue, will retry automatically');
}
}📚 Documentation
📄 License
MIT License - see LICENSE file for details.
🙏 Acknowledgments
- PokeAPI for providing the Pokemon data
- Built with ❤️ for the developer community
Ready to catch 'em all with type safety? 🏆
const client = new PokeApiClient();
const pikachu = await client.getPokemon('pikachu');
// Fully typed, no runtime surprises! ⚡