quick-axios-cache
v1.0.0
Published
A simple, lightweight, and customisable in-memory cache for Axios requests with TTL.
Maintainers
Readme
quick-axios-cache
A simple, lightweight, and customisable in-memory cache for Axios requests with Time-To-Live (TTL) support.
Features
- 🚀 Transparent Caching — wraps any Axios instance, requiring no changes to your existing request calls.
- ⏱️ TTL Support — configures how long cached items are valid.
- 🛠️ Custom Key Building — customisable key generation based on method, URL, params, or request data.
- 📦 Control Interface — clear the cache, inspect the cache size, or delete specific keys on demand.
- 🛡️ Safe Copying — returns clones of cached responses to prevent mutation side-effects.
Installation
npm install quick-axios-cacheNote: axios is required as a peer dependency.
Usage
const axios = require('axios');
const { setupCache } = require('quick-axios-cache');
// Create an Axios instance
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
// Enable caching (with 10-second TTL)
const cacheController = setupCache(api, {
ttl: 10000, // 10 seconds in ms
onCacheHit: (key) => console.log(`[Cache Hit] Key: ${key}`),
onCacheMiss: (key) => console.log(`[Cache Miss] Key: ${key}`)
});
async function run() {
// First call -> Cache Miss (fetches from network)
const res1 = await api.get('/todos/1');
console.log('Fetched Todo 1:', res1.data.title);
// Second call within 10s -> Cache Hit (returns from memory)
const res2 = await api.get('/todos/1');
console.log('Fetched Todo 1 (Cached):', res2.data.title);
console.log('Is Cached:', res2.headers['x-axios-cache'] === 'HIT'); // true
// Inspect or clear cache
console.log('Cache Size:', cacheController.size); // 1
cacheController.clear();
console.log('Cache Size after clear:', cacheController.size); // 0
}
run();Options
setupCache(axiosInstance, options) accepts the following options:
| Option | Type | Default | Description |
|---|---|---|---|
| ttl | number | 60000 | Time-to-Live in milliseconds. |
| methods | Array<string> | ['get'] | HTTP methods to cache (must be lowercase). |
| buildCacheKey | Function | Default Key Builder | A function (config) => string that returns a unique cache key based on the request config. |
| onCacheHit | Function | () => {} | Callback invoked on cache hit. |
| onCacheMiss | Function | () => {} | Callback invoked on cache miss. |
Controller API
setupCache returns a controller object:
const cacheController = setupCache(api);
cacheController.clear(); // Clears the entire cache
cacheController.delete(key); // Deletes a specific cache key
cacheController.getCache(); // Returns the internal Map instance
console.log(cacheController.size); // Get total cached items countLicense
MIT
