A lightweight, offline-first caching library for JavaScript applications running in browsers or service workers. It wraps the native Fetch API and Cache Storage to provide resilient data fetching with configurable caching strategies, ensuring your app wor
npm install offline-first-cache-wrappercacheFirst, networkFirst, and staleWhileRevalidate for flexible caching behavior.
bash
npm install offline-first-cache-wrapper
`
Or clone the repository and build locally.
Usage
$3
`javascript
import { CacheWrapper, strategies } from 'offline-first-cache-wrapper';
// Create an instance with default cache-first strategy
const cacheWrapper = new CacheWrapper({
cacheName: 'my-app-cache',
defaultStrategy: strategies.cacheFirst,
onHit: (request, response) => console.log('Cache hit for:', request),
onMiss: (request) => console.log('Cache miss for:', request)
});
// Fetch data with caching
const response = await cacheWrapper.fetch('/api/data');
const data = await response.json();
`
$3
`javascript
// Network-first for fresh data
const freshResponse = await cacheWrapper.fetch('/api/live-data', {}, strategies.networkFirst);
// Stale-while-revalidate for background updates
const swrResponse = await cacheWrapper.fetch('/api/static-data', {}, strategies.staleWhileRevalidate);
`
$3
`javascript
const results = await cacheWrapper.prefetch([
'/api/resource1',
'/api/resource2'
], {}, 3); // Concurrency limit of 3
console.log(results); // Array of { url, ok, error? }
`
$3
`javascript
// Invalidate a specific URL
await cacheWrapper.invalidate('/api/old-data');
// Clear entire cache
await cacheWrapper.clear();
// List cached URLs
const cachedUrls = await cacheWrapper.keys();
console.log(cachedUrls);
`
API Reference
$3
- constructor(options): Initializes the wrapper.
- options.cacheName (string): Name of the cache (default: 'ofcw-v1').
- options.defaultStrategy (function): Default caching strategy (default: strategies.cacheFirst).
- options.onHit(request, response): Callback for cache hits.
- options.onMiss(request): Callback for cache misses.
- fetch(input, options?, strategy?): Fetches with caching. Returns a Promise.
- input: URL string or Request object.
- options: Fetch options (e.g., headers).
- strategy: Override default strategy.
- fetchText(input, options?, strategy?): Fetches and returns response text.
- prefetch(urls, options?, concurrency?): Prefetches multiple URLs. Returns Promise>.
- invalidate(url): Removes a URL from cache. Returns Promise.
- clear(): Deletes the entire cache. Returns Promise.
- keys(): Lists cached URLs. Returns Promise>.
$3
- strategies.cacheFirst(request, options, cacheName): Prioritizes cache, falls back to network.
- strategies.networkFirst(request, options, cacheName): Prioritizes network, falls back to cache.
- strategies.staleWhileRevalidate(request, options, cacheName): Returns cached data immediately, updates in background.
$3
Exposed for advanced use: openCache, match, put, delete, keys, clear.
Examples
$3
`javascript
// In service-worker.js
importScripts('path/to/offline-first-cache-wrapper/index.js');
const { CacheWrapper, strategies } = self.offlineFirstCacheWrapper; // Assuming global export
const cacheWrapper = new CacheWrapper({ cacheName: 'sw-cache' });
self.addEventListener('fetch', (event) => {
if (event.request.url.includes('/api/')) {
event.respondWith(cacheWrapper.fetch(event.request, {}, strategies.networkFirst));
}
});
`
$3
For testing, use polyfills:
`bash
npm install node-fetch whatwg-fetch
`
`javascript
global.fetch = require('node-fetch');
global.Request = require('node-fetch').Request;
global.Response = require('node-fetch').Response;
// Polyfill Cache API if needed (e.g., via 'cache-polyfill')
``