TypeFetched/examples/advanced-features.ts
Casey Collier b85b9a63e2 Initial commit: TypedFetch - Zero-dependency, type-safe HTTP client
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
2025-07-20 12:35:43 -04:00

69 lines
No EOL
1.8 KiB
TypeScript

import { tf, createTypedFetch } from '../src/index.js'
// Auto-discovery example
async function discoveryExample() {
console.log('=== API Discovery ===')
const api = await tf.discover('https://api.github.com')
// TypeScript knows about the endpoints!
const repos = await api.users.github.repos.get()
console.log(`GitHub has ${repos.length} public repos`)
}
// Custom instance with defaults
async function customInstanceExample() {
console.log('\n=== Custom Instance ===')
const api = createTypedFetch()
// All requests through this instance share config
const user = await api.get('https://api.github.com/users/torvalds')
console.log('User:', user.name)
}
// Working with different HTTP methods
async function httpMethodsExample() {
console.log('\n=== HTTP Methods ===')
const baseUrl = 'https://jsonplaceholder.typicode.com'
// GET
const posts = await tf.get(`${baseUrl}/posts?userId=1`)
console.log(`User 1 has ${posts.length} posts`)
// PUT (update)
const updated = await tf.put(`${baseUrl}/posts/1`, {
id: 1,
title: 'Updated title',
body: 'Updated body',
userId: 1
})
console.log('Updated post:', updated.title)
// DELETE
await tf.delete(`${baseUrl}/posts/1`)
console.log('Post deleted')
}
// Caching demonstration
async function cachingExample() {
console.log('\n=== Caching Demo ===')
// First request hits network
console.time('First request')
await tf.get('https://api.github.com/users/octocat')
console.timeEnd('First request')
// Second request uses cache (much faster!)
console.time('Cached request')
await tf.get('https://api.github.com/users/octocat')
console.timeEnd('Cached request')
}
// Run all examples
async function main() {
await discoveryExample()
await customInstanceExample()
await httpMethodsExample()
await cachingExample()
}
main().catch(console.error)