Features: - Zero configuration, just works out of the box - Runtime type inference and validation - Built-in caching with W-TinyLFU algorithm - Automatic retries with exponential backoff - Circuit breaker for resilience - Request deduplication - Offline support with queue - OpenAPI schema discovery - Full TypeScript support with type descriptors - Modular architecture - Configurable for advanced use cases Built with bun, ready for npm publishing
3.7 KiB
3.7 KiB
TYPEDFETCH MANUAL - REFERENCE DOCUMENT
TypedFetch Core API
import { tf } from 'typedfetch'
// Basic methods
tf.get<T>(url, options?)
tf.post<T>(url, body?, options?)
tf.put<T>(url, body?, options?)
tf.delete<T>(url, options?)
// Advanced features
tf.discover(baseURL)
tf.addRequestInterceptor(fn)
tf.addResponseInterceptor(fn)
tf.getMetrics()
tf.resetCircuitBreaker()
tf.getAllTypes()
tf.getTypeInfo(endpoint)
tf.getInferenceConfidence(endpoint)
// Streaming & special
tf.stream(url)
tf.streamJSON(url)
tf.upload(url, file)
tf.graphql(url, query, variables?)
Standard Examples
- Basic GET:
await tf.get('https://api.example.com/users')
- Typed GET:
await tf.get<User[]>('https://api.example.com/users')
- POST with data:
await tf.post('https://api.example.com/users', { name: 'John' })
- Error handling:
try { ... } catch (error) { console.log(error.suggestions) }
- With interceptor:
tf.addRequestInterceptor(config => { ... })
Test APIs We Use
- Beginner:
- httpbin.org (simple echo/test endpoints)
- jsonplaceholder.typicode.com (fake REST API)
- Intermediate:
- api.github.com (real-world API)
- openweathermap.org/api (requires API key)
- Advanced:
- Custom mock servers
- GraphQL endpoints
Key Concepts by Chapter
Chapter 1: What the Hell is an API Anyway?
- APIs as restaurant waiters metaphor
- HTTP protocol basics
- JSON data format
- Request/Response cycle
- HTTP methods overview
- Status codes introduction
- fetch() API basics
Chapter 2: Enter TypedFetch - Your API Superpower
- TypedFetch installation (npm install typedfetch)
- tf.get() basic usage
- Automatic JSON parsing
- Enhanced error messages with suggestions
- Zero configuration philosophy
- Request deduplication
- Built-in caching introduction
- tf.enableDebug() for development
Chapter 3: The Magic of GET Requests
- Query parameters with params option
- Headers in detail (Authorization, Accept, custom)
- Pagination patterns (page-based and generators)
- Polling for real-time updates
- Parallel requests with Promise.all()
- Conditional requests (ETags)
- Request/Response interceptors
- Response transformation
Chapter 4: POST, PUT, DELETE - The Full CRUD
- CRUD operations overview
- POST for creating resources
- PUT vs PATCH (complete vs partial updates)
- DELETE operations
- Different content types (JSON, FormData, URLSearchParams)
- Optimistic updates pattern
- Bulk operations
- Idempotency keys for safe retries
- Conditional updates with ETags
- Authentication with Bearer tokens
- Ch5: Error handling (Smart errors)
- Ch6: Caching (W-TinyLFU algorithm)
- Ch7: Type safety (Runtime inference + manual types)
- Ch8: Interceptors (Request/response pipeline)
- Ch9: Streaming (Real-time data)
- Ch10: Performance (Deduplication, circuit breaker)
- Ch11: Offline support (Queue & sync)
- Ch12: Testing (Mocking & debugging)
- Ch13: Abstractions (Repository pattern)
- Ch14: Framework integration (React, Vue, Angular)
- Ch15: Future tech (HTTP/3, GraphQL)
Naming Conventions
// Variables
const response = await tf.get() // Not: res, result, data
const user = response.data // Not: userData, u, person
const error = catch(err) // Not: e, error, exception
// URLs
const API_BASE = 'https://api.example.com'
const USERS_ENDPOINT = `${API_BASE}/users`
const USER_ENDPOINT = (id) => `${API_BASE}/users/${id}`
// Types
interface User { } // Not: IUser, UserType
type UserList = User[] // Not: Users, UserArray
Progressive Example App
WeatherBuddy - Evolves throughout the book:
- Ch1-3: Display current weather
- Ch4-6: User preferences (location, units)
- Ch7-9: Type-safe, cached, real-time updates
- Ch10-12: Offline support, testing
- Ch13-15: Full architecture, multiple frameworks