offline-first-cache-wrapper
v1.0.1
Published
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
Readme
Offline-First Cache Wrapper
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 works seamlessly offline or with poor network conditions.
Features
- Offline-First Strategies: Supports
cacheFirst,networkFirst, andstaleWhileRevalidatefor flexible caching behavior. - Browser-Native: Leverages the Cache API and Fetch API, no external dependencies required.
- Simple API: Easy-to-use wrapper class with hooks for cache hits/misses.
- Prefetching: Batch prefetch URLs with concurrency control.
- Cache Management: Methods to invalidate, clear, or list cached items.
- Lightweight: Minimal footprint, suitable for progressive web apps (PWAs).
Installation
Install via npm:
npm install offline-first-cache-wrapperOr clone the repository and build locally.
Usage
Basic Setup
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();Using Different Strategies
// 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);Prefetching
const results = await cacheWrapper.prefetch([
'/api/resource1',
'/api/resource2'
], {}, 3); // Concurrency limit of 3
console.log(results); // Array of { url, ok, error? }Cache Management
// 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
CacheWrapper Class
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<Array<{url, ok, error?}>>.invalidate(url): Removes a URL from cache. Returns Promise.clear(): Deletes the entire cache. Returns Promise.keys(): Lists cached URLs. Returns Promise<Array>.
Strategies
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.
CacheManager (Internal)
Exposed for advanced use: openCache, match, put, delete, keys, clear.
Examples
Service Worker Integration
// 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));
}
});Testing in Node.js
For testing, use polyfills:
npm install node-fetch whatwg-fetchglobal.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')Limitations
- Requires a browser environment with Cache API support (modern browsers or service workers).
- For Node.js, provide polyfills for Fetch and Cache APIs.
- Responses are cloned when caching to avoid single-use issues.
- No built-in error handling for cache quota exceeded (browsers handle this).
Contributing
Contributions welcome! Open issues or PRs on GitHub. Ensure tests pass and add examples for new features.
License
MIT License. See LICENSE file for details.
Changelog
- v1.0.0: Initial release with core caching strategies and API.
