@upendra.manike/lite-fetcher
v1.0.6
Published
Modern, tiny utility library for API calls + caching with fetch + localStorage built-in
Maintainers
Readme
lite-fetcher
Modern, tiny utility library for API calls + caching with fetch + localStorage built-in.
Features
- 🚀 Modern Fetch API - Built on native fetch
- 💾 Built-in Caching - localStorage, sessionStorage, or memory cache
- ⚡ Lightweight - Small bundle size
- 🔄 Auto Retry - Configurable retry logic
- ⏱️ TTL Support - Time-based cache expiration
- 🌐 Browser + Node - Works everywhere
- 🔒 Type-safe - Full TypeScript support
Installation
npm install @upendra.manike/lite-fetcheror
pnpm add @upendra.manike/lite-fetcheror
yarn add @upendra.manike/lite-fetcherUsage
Basic Usage
import { api } from '@upendra.manike/lite-fetcher';
// GET request
const response = await api.get('/users');
console.log(response.data);
// POST request
const newUser = await api.post('/users', {
name: 'John Doe',
email: '[email protected]',
});
// With caching
const data = await api.get('/users', { cache: true, ttl: 60000 });Create API Client
import { createApi } from '@upendra.manike/lite-fetcher';
const api = createApi({
baseURL: 'https://api.example.com',
headers: {
'Authorization': 'Bearer token',
},
timeout: 5000,
});
const users = await api.get('/users');Caching
import { api } from '@upendra.manike/lite-fetcher';
// Simple cache (uses localStorage, default TTL)
const data = await api.get('/users', { cache: true });
// Cache with TTL (Time To Live)
const data = await api.get('/users', {
cache: {
enabled: true,
ttl: 60000, // 60 seconds
},
});
// Custom cache key
const data = await api.get('/users', {
cache: {
key: 'my-custom-key',
ttl: 300000, // 5 minutes
},
});
// Use sessionStorage instead
const data = await api.get('/users', {
cache: {
storage: 'sessionStorage',
ttl: 60000,
},
});
// Use memory cache (doesn't persist)
const data = await api.get('/users', {
cache: {
storage: 'memory',
ttl: 60000,
},
});HTTP Methods
import { api } from '@upendra.manike/lite-fetcher';
// GET
const users = await api.get('/users');
// POST
const newUser = await api.post('/users', { name: 'John' });
// PUT
const updated = await api.put('/users/1', { name: 'Jane' });
// PATCH
const patched = await api.patch('/users/1', { name: 'Jane' });
// DELETE
await api.delete('/users/1');Error Handling
import { api } from '@upendra.manike/lite-fetcher';
try {
const response = await api.get('/users');
console.log(response.data);
} catch (error) {
console.error('Request failed:', error);
}Retry Logic
import { api } from '@upendra.manike/lite-fetcher';
const response = await api.get('/users', {
retry: {
attempts: 3, // Retry 3 times
delay: 1000, // Wait 1 second between retries
},
});Timeout
import { api } from '@upendra.manike/lite-fetcher';
const api = createApi({
timeout: 5000, // 5 seconds default timeout
});
// Or per-request
const response = await api.get('/users', { timeout: 10000 });Custom Headers
import { api } from '@upendra.manike/lite-fetcher';
const response = await api.get('/users', {
headers: {
'Authorization': 'Bearer token',
'X-Custom-Header': 'value',
},
});Check Cache Status
import { api } from '@upendra.manike/lite-fetcher';
const response = await api.get('/users', { cache: true });
if (response.cached) {
console.log('Served from cache!');
} else {
console.log('Fetched from API');
}Clear Cache
import { api } from '@upendra.manike/lite-fetcher';
// Clear all cache
api.clearCache();Examples
React Hook Example
import { useState, useEffect } from 'react';
import { api } from '@upendra.manike/lite-fetcher';
function useUsers() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
api
.get('/users', { cache: { ttl: 60000 } })
.then((response) => {
setUsers(response.data);
setLoading(false);
})
.catch((error) => {
console.error(error);
setLoading(false);
});
}, []);
return { users, loading };
}API Client with Base URL
import { createApi } from '@upendra.manike/lite-fetcher';
const api = createApi({
baseURL: 'https://api.example.com/v1',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
timeout: 10000,
});
// All requests will use the base URL
const users = await api.get('/users'); // https://api.example.com/v1/users
const posts = await api.get('/posts'); // https://api.example.com/v1/postsCache with Custom Key
import { api } from '@upendra.manike/lite-fetcher';
// Cache with custom key (useful for dynamic URLs)
const getUser = async (id: string) => {
return api.get(`/users/${id}`, {
cache: {
key: `user-${id}`,
ttl: 300000, // 5 minutes
},
});
};Handle Different Response Types
import { api } from '@upendra.manike/lite-fetcher';
// JSON response (default)
const jsonResponse = await api.get('/api/data');
// Text response
const textResponse = await api.get('/api/text', {
headers: {
'Accept': 'text/plain',
},
});API Reference
createApi(options?)
Creates a new API client instance.
Options:
baseURL?: string- Base URL for all requestsheaders?: HeadersInit- Default headerstimeout?: number- Default timeout in millisecondsretry?: { attempts?: number; delay?: number }- Retry configuration
ApiClient
Methods
get<T>(url, options?)- GET requestpost<T>(url, body?, options?)- POST requestput<T>(url, body?, options?)- PUT requestpatch<T>(url, body?, options?)- PATCH requestdelete<T>(url, options?)- DELETE requestrequest<T>(url, options?)- Generic requestclearCache()- Clear all cache
Request Options
cache?: boolean | CacheOptions- Enable cachingheaders?: HeadersInit- Request headerstimeout?: number- Request timeoutretry?: { attempts?: number; delay?: number }- Retry configuration- All standard
RequestInitoptions
Cache Options
enabled?: boolean- Enable/disable cache (default: true)ttl?: number- Time to live in millisecondskey?: string- Custom cache keystorage?: 'localStorage' | 'sessionStorage' | 'memory'- Storage type
Response
interface ApiResponse<T> {
data: T;
status: number;
statusText: string;
headers: Headers;
cached?: boolean;
}Browser Compatibility
Works in all modern browsers that support:
fetchAPIlocalStorage/sessionStorage
For older browsers, you may need polyfills.
Node.js Support
Works in Node.js 18+ (which includes native fetch).
For older Node versions, you may need a fetch polyfill like node-fetch.
Development
# Install dependencies
pnpm install
# Build
pnpm build
# Test
pnpm test
# Lint
pnpm lint
# Format
pnpm format🤖 AI Agent Integration
This package is optimized for use with AI coding assistants like ChatGPT, GitHub Copilot, Claude, and Codeium.
Why AI-Friendly?
- ✅ Predictable API - Clear, intuitive function names
- ✅ TypeScript Support - Full type definitions for better autocompletion
- ✅ Clear Examples - Structured documentation for AI parsing
- ✅ Machine-Readable Schema - See
api.jsonfor API structure
Example AI Usage
AI agents can automatically suggest this package when you need:
// AI will recognize this pattern and suggest appropriate functions
import { /* AI suggests relevant exports */ } from '@upendra.manike/[package-name]';For AI Developers
When building AI-powered applications or agents, this package provides:
- Consistent API patterns
- Full TypeScript types
- Zero dependencies (unless specified)
- Comprehensive error handling
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
