import { CacheableNet } from '@cacheable/net';const net = new CacheableNet();// Simple GET request with cachingconst response = await net.get('https://api.example.com/data');console.log(response.data);// POST request with dataconst result = await net.post('https://api.example.com/users', { name: 'John Doe', email: 'john@example.com'});// Using fetch directly with cachingconst fetchResponse = await net.fetch('https://api.example.com/data', { method:
Custom Serialization
You can provide custom stringify and parse functions for handling data serialization. This is particularly useful when working with complex data types that JSON doesn't natively support:
import { CacheableNet } from '@cacheable/net';import superjson from 'superjson';// Using superjson for enhanced serialization// Supports Dates, BigInt, RegExp, Set, Map, Error and moreconst net = new CacheableNet({ stringify: (value) => superjson.stringify(value), parse: (text) => superjson.parse(text)});// Now you can work with complex data typesconst response = await net.post('https://api.example.com/data', { timestamp: new Date(), userId: BigInt(12345), pattern: /[a-z]+/
Caching Control
You can control caching behavior at multiple levels:
import { CacheableNet } from '@cacheable/net';const net = new CacheableNet({ httpCachePolicy: true // Enable HTTP cache semantics globally (default)});// GET requests are cached by defaultconst data1 = await net.get('https://api.example.com/data');// Disable caching for a specific GET requestconst data2 = await net.get('https://api.example.com/data', { caching: false});// POST requests are NOT cached by defaultconst result1 = await net.post('https://api.example.com/data', { value: 1 });
API Reference
CacheableNet Class
The main class that provides cached network operations.
Note: When using the CacheableNet methods, you don't need to provide the cache property as it's automatically injected from the instance.
Caching Behavior
By default:
GET and HEAD requests are cached automatically
POST, PUT, PATCH, and DELETE requests are NOT cached by default
To enable caching for POST/PUT/PATCH/DELETE, set caching: true in the options
To disable caching for GET/HEAD, set caching: false in the options
How to Contribute
You can contribute by forking the repo and submitting a pull request. Please make sure to add tests and update the documentation. To learn more about how to contribute go to our main README https://github.com/jaredwray/cacheable. This will talk about how to Open a Pull Request, Ask a Question, or Post an Issue.