🚀 axios-cache-adapter
Caching adapter for axios. Store request results in a configurable store to prevent unneeded network requests.
Adapted from superapi-cache by @stephanebachelier
Note: Per request override does not work with axios@0.19.0
as mentioned in this issue. Until it is fixed, axios-cache-adapter
locks the axios
version to 0.18.1
Install
Using npm
npm install --save axios-cache-adapter
Or bower
bower install --save axios-cache-adapter
Or from a CDN like unpkg.com
Usage
Instantiate adapter on its own
You can instantiate the axios-cache-adapter
on its own using the setupCache()
method and then attach the adapter manually to an instance of axios
.
// Import dependencies // Create `axios-cache-adapter` instanceconst cache = // Create `axios` instance passing the newly created `cache.adapter`const api = axios // Send a GET request to some REST api
Instantiate axios with bound adapter
You can use the setup()
method to get an instance of axios
pre-configured with the axios-cache-adapter
. This will remove axios
as a direct dependency in your code.
// Import dependencies // Create `axios` instance with pre-configured `axios-cache-adapter` attached to itconst api = // Send a GET request to some REST apiapi
Override instance config with per request options
After setting up axios-cache-adapter
with a specific cache configuration you can override parts of that configuration on individual requests.
const api = // Use global instance configapi // Override `maxAge` and cache URLs with query parametersapi
Note: Not all instance options can be overridden per request, see the API documentation at the end of this readme
Use localforage as cache store
You can give a localforage
instance to axios-cache-adapter
which will be used to store cache data instead of the default in memory store.
Note: This only works client-side because localforage
does not work in Node.js
// `async` wrapper to configure `localforage` and instantiate `axios` with `axios-cache-adapter` { // Register the custom `memoryDriver` to `localforage` await localforage // Create `localforage` instance const forageStore = localforage // Create `axios` instance with pre-configured `axios-cache-adapter` using a `localforage` store return }
Use redis as cache store
You can give a RedisStore
instance to axios-cache-adapter
which will be used to store cache data instead of the default in memory store.
Note: This only works server-side
const setup RedisStore = const redis = const client = redisconst store = clientconst api = const response = await api
Check if response is served from network or from cache
When a response is served from cache a custom response.request
object is created with a fromCache
boolean.
// Import dependencies // Create `axios` instance with pre-configured `axios-cache-adapter`const api = // Wrap code in an `async` function { // First request will be served from network const response = await api // `response.request` will contain the origin `axios` request object assert // Second request to same endpoint will be served from cache const anotherResponse = await api // `response.request` will contain `fromCache` boolean assert} // Execute our `async` wrapper
Read stale cache data on network error
You can tell axios-cache-adapter
to read stale cache data when a network error occurs using the readOnError
option.
readOnError
can either be a Boolean
telling cache adapter to attempt reading stale cache when any network error happens or a Function
which receives the error and request objects and then returns a Boolean
.
By default axios-cache-adapter
clears stale cache data automatically, this would conflict with activating the readOnError
option, so the clearOnStale
option should be set to false
.
const api = // Make a first successful request which will store the response in cacheapi // Let's say that the stored data has become stale (default 15min max age has passed)// and we make the same request but it results in an internal server error (status=500)api
Note: Passing a function to readOnError
is a smarter thing to do as you get to choose when a stale cache read should be attempted instead of doing it on all kind of errors
Invalidate cache entries
By default, a cache entry will be invalidated when the request method is not GET
, POST
, PUT
, PATCH
or DELETE
if it is made to the same URL using the following method:
async { const method = requestmethod if method !== 'get' await configstore }
You can customize how axios-cache-adapter
invalidates stored cache entries by providing a custom invalidate
function.
// Create cached axios instance with custom invalidate methodconst api = // Make a request that will get stored into cacheapi // Wait some time // Make another request to same end point but force cache invalidationapi
maxAge
Use response headers to automatically set When you set the readHeaders
option to true
, the adapter will try to read cache-control
or expires
headers to automatically set the maxAge
option for the given request.
const api = // Make a request which will respond with header `cache-control: max-age=60`api // Make a request which responds with header `cache-control: no-cache`api
Note: For the cache-control
header, only the max-age
, no-cache
and no-store
values are interpreted.
API
setupCache(options)
Create a cache adapter instance. Takes an options
object to configure how the cached requests will be handled,
where they will be stored, etc.
Options
// Options passed to `setupCache()`. // {Number} Maximum time for storing each request in milliseconds, // defaults to 15 minutes when using `setup()`. maxAge: 0 // {Number} Maximum number of cached request (last in, first out queue system), // defaults to `false` for no limit. *Cannot be overridden per request* limit: false // {Object} An instance of localforage, defaults to a custom in memory store. // *Cannot be overridden per request* store: // {String|Function} Generate a unique cache key for the request. // Will use request url and serialized params by default. requrl + // {Function} Invalidate stored cache. By default will remove cache when // making a request with method not `GET`, `POST`, `PUT`, `PATCH` or `DELETE` query. invalidate: async { const method = reqmethod if method !== 'get' await cfgstore } // {Object} Define which kind of requests should be excluded from cache. exclude: // {Array} List of regular expressions to match against request URLs. paths: // {Boolean} Exclude requests with query parameters. query: true // {Function} Method which returns a `Boolean` to determine if request // should be excluded from cache. filter: null // {Boolean} Clear cached item when it is stale. clearOnStale: true // {Boolean} Clear all cache when a cache write error occurs // (prevents size quota problems in `localStorage`). clearOnError: true // {Function|Boolean} Determine if stale cache should be read when a network error occurs. readOnError: false // {Boolean} Determine if response headers should be read to set `maxAge` automatically. // Will try to parse `cache-control` or `expires` headers. readHeaders: false // {Boolean} Ignore cache, will force to interpret cache reads as a `cache-miss`. // Useful to bypass cache for a given request. ignoreCache: false // {Function|Boolean} Print out debug log to console. debug: false
Returns
setupCache()
returns an object containing the configured adapter
, the cache store
and the config
that is applied to this instance.
setup(options)
Create an axios
instance pre-configured with the cache adapter. Takes an options
object to configure the cache and
axios at the same time.
Options
cache: // Options passed to the `setupCache()` method // Options passed to `axios.create()` method
All the other parameters will be passed directly to the axios.create
method.
Returns
setup()
returns an instance of axios
pre-configured with the cache adapter.
The cache store
is conveniently attached to the axios
instance as instance.cache
for easy access.
RedisStore(client, [, hashKey])
RedisStore allow you to cache requests on server using redis.
Create a RedisStore
instance. Takes client
(RedisClient
) and optional hashKey
(name of hashSet to be used in redis).
client
// Using redis client https://github.com/NodeRedis/node_redis // We have tested it with node_redis v.2.8.0 but it's supposed to work smoothly with the comming releases. const redis = const client = redis
Returns
new RedisStore()
returns an instance of RedisStore
to be passed to setupCache() as store
in config object.
Per request options
Using the same object definition as the setup
method you can override cache options for individual requests.
api
All options except limit
and store
can be overridden per request.
Also the following keys are used internally and therefore should not be set in the options: adapter
, uuid
, acceptStale
.
Building
npm run build
Webpack is used to build umd versions of the library that are placed in the dist
folder.
cache.js
cache.min.js
cache.node.js
cache.node.min.js
A different version of axios-cache-adapter
is generated for node and the browser due to how Webpack 4 uses a target
to change how the UMD wrapper is generated using global
or window
. If you are using the library in node or in your front-end code while using a module bundler (Webpack, rollup, etc) the correct version will be picked up automatically thanks to the "main"
and "browser"
fields in the package.json
.
axios-cache-adapter
is developped in ES6+ and uses async/await syntax. It is transpiled to ES5 using babel
with preset-env
.
Testing
Tests are executed using karma.
To launch a single run tests using ChromeHeadless:
npm test
To launch tests in watch mode in Chrome for easier debugging with devtools:
npm run watch
Browser vs Node.js
axios-cache-adapter
was designed to run in the browser. It does work in nodejs using the in memory store. But storing data in memory is not the greatests idea ever.
You can give a store
to override the in memory store but it has to comply with the localForage
API and localForage
does not work in nodejs for very good reasons that are better explained in this issue.
The better choice if you want to use axios-cache-adapter
server-side is to use a redis server with a RedisStore
instance as explained above in the API section.
License
MIT © Carl Ogren