Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
axios-cache-interceptor
Advanced tools
The axios-cache-interceptor package is a middleware for Axios that provides caching capabilities. It allows you to cache HTTP requests and responses, reducing the number of network requests and improving performance.
Basic Caching
This feature allows you to set up basic caching for your Axios requests. The example demonstrates how to create a cache with a maximum age of 15 minutes and use it with an Axios instance.
const axios = require('axios');
const { setupCache } = require('axios-cache-interceptor');
const cache = setupCache({
maxAge: 15 * 60 * 1000 // 15 minutes
});
const api = axios.create({
adapter: cache.adapter
});
api.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
Custom Cache Key
This feature allows you to define a custom cache key. The example shows how to create a cache key based on the request URL, method, and parameters.
const axios = require('axios');
const { setupCache } = require('axios-cache-interceptor');
const cache = setupCache({
key: req => req.url + req.method + JSON.stringify(req.params)
});
const api = axios.create({
adapter: cache.adapter
});
api.get('https://api.example.com/data', { params: { id: 1 } })
.then(response => console.log(response.data))
.catch(error => console.error(error));
Cache Invalidation
This feature allows you to manually invalidate the cache for specific requests. The example demonstrates how to invalidate the cache for a specific URL.
const axios = require('axios');
const { setupCache } = require('axios-cache-interceptor');
const cache = setupCache();
const api = axios.create({
adapter: cache.adapter
});
api.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
// Invalidate the cache for a specific request
cache.invalidate({ url: 'https://api.example.com/data' });
axios-cache-adapter is another caching library for Axios. It provides similar functionality to axios-cache-interceptor, allowing you to cache HTTP requests and responses. However, axios-cache-adapter offers more configuration options for cache storage, such as using localStorage or a custom store.
axios-extensions is a package that extends Axios with additional features, including caching. It provides a simple way to add caching to your Axios requests and supports various cache strategies. Compared to axios-cache-interceptor, axios-extensions offers more flexibility in defining cache strategies and expiration times.
axios-cache-interceptor
is a axios wrapper for caching and preventing unneeded requestsimport axios from 'axios';
import { useCache, SessionCacheStorage } from 'axios-cache-interceptor';
// An axios instance with modified types
const api = useCache(axios.create(), {
/* options */
});
// Make a simple request, with caching support, to the api
const resp1 = await api.get('https://api.example.com/');
// resp1.cached = false
const resp2 = await api.get('https://api.example.com/');
// resp2.cached = true
Axios must be installed separately.
npm install --save axios axios-cache-interceptor
# or
yarn add axios axios-cache-interceptor
const { useCache } = require('axios-cache-interceptor');
// or
import { useCache } from 'axios-cache-interceptor';
<!-- Replace VERSION with the desired version -->
<script
crossorigin
src="https://cdn.jsdelivr.net/npm/axios-cache-interceptor@VERSION/dist/index.bundle.js"
></script>
<!-- or -->
<script
crossorigin
src="https://unpkg.com/axios-cache-interceptor@VERSION/dist/index.bundle.js"
></script>
const { useCache } = window.AxiosCacheInterceptor;
Below you can check what version of this package is supported by your version of axios. But that does not mean that won't work with any version. Most of "breaking changes" made by axios was it's types.
NOTE: Below v0.3, axios was not configured as a peer dependency
Version | Axios |
---|---|
~v0.5 | >= v0.24 |
~v0.4 | >= v0.23 |
~v0.3 | >= v0.22 |
<= v0.2 | v0.21 |
To you use this cache interceptor, you can apply to an existing instance or create a new one.
import { useCache } from 'axios-cache-interceptor';
// Your axios instance
let axios;
// Return the same axios instance, but with a modified Typescript type.
axios = useCache(axios, {
/* options here */
});
After that, you can made your own requests normally.
The compiled code is built in two different ways, one as nodejs module and one as a
browser. Both of them uses Babel with
Browserslist default
preset.
You can see more here about compiling options:
If, for some reason, you have a bug with the compiled code, such as a user have an incompatible browser, please contact me.
A good thing to know is that every request passed through this interceptor, has an id. This does not mean that is a unique id. The id is used in a number of ways, but the most important is to bind a request to its cache.
The id generation is good enough to generate the same id for theoretically sames requests.
The example of this is a request with { baseUrl: 'https://a.com/', url: '/b' }
results
to the same id with { url: 'https://a.com/b/' }
.
Also, a custom id can be used to treat two requests as the same.
axios.get('...', {
id: 'my-custom-id',
cache: {
// other properties...
}
});
The default id generation can clarify this idea.
Every response that came from our custom axios instance, will have some extras properties, that you can retrieve like that:
const result = await cache.get(/* ... */);
const id = result['propertyName'];
A simple boolean to check whether this request was cached or not.
NOTE: The first response of a request capable of being cached will return
cached: false
, as only your next requests will return cached: true
.
The request id resolved. This property represents the ID used throughout the internal code. Remember that, depending on the config.keyGenerator, it can be different as the provided on the request.id.
When applying the interceptor, you can customize some properties:
const axios = useCache(axios, {
// Properties here
});
The storage used to save the cache. Here will probably be the most changed property. Defaults to MemoryStorage.
You can create your own implementation by implementing CacheStorage.
There are few built in storage implementations, you can use them by importing:
With the cdn served bundle, the MemoryStorage and BrowserAxiosStorage comes by default. Just get them by
window.AxiosCacheInterceptor.BrowserAxiosStorage
orwindow.AxiosCacheInterceptor.MemoryAxiosStorage
.
import {} from 'axios-cache-interceptor/dist/storage/{name}';
import 'axios-cache-interceptor/dist/storage/memory';
import 'axios-cache-interceptor/dist/storage/browser';
The function used to create different keys for each request. Defaults to a function that priorizes the id, and if not specified, a string is generated using the method, baseUrl, params, and url.
A simple object that will hold a promise for each pending request. Used to handle concurrent requests.
Can also be used as type of listener to know when a request is finished.
The function used to interpret all headers from a request and determine a time to live
(ttl
) number.
Check out the inline documentation to know how to modify your own.
The used request and response interceptor. Basically the core function of this library. Check out the used request and response to see the default used.
By using this axios client and using an ide with intellisense, you'll see a custom
property called cache
.
The inline documentation is self explanatory, but here are some examples and information:
You can override the request id used by this property.
The time that the request will remain in cache. Some custom storage implementations may not respect 100% the time.
When using interpretHeader
, this value is ignored.
If activated, when the response is received, the ttl
property will be inferred from the
requests headers. See the actual implementation of the
interpretHeader
method for more information. You can
override the default behavior by setting the headerInterpreter
when creating the cached
axios client.
Specify what request methods should be cached.
Defaults to only GET
methods.
An object or function that will be tested against the response to test if it can be cached. See the inline documentation for more.
An simple example with all values:
axios.get('url', {
cache: {
cachePredicate: {
// Only cache if the response comes with a *good* status code
statusCheck: [200, 399],
// Tests against any header present in the response.
containsHeader: {
'x-custom-header': true,
'x-custom-header-2': 'only if matches this string',
'x-custom-header-3': (value) => /* some calculation */ true
},
// Check custom response body
responseMatch: (response) => {
// Sample that only caches if the response is authenticated
return response.auth.status === 'authenticated':
}
}
}
});
Once the request is resolved, this specifies what other responses should change their
cache. Can be used to update the request or delete other caches. It is a simple Record
with the request id.
Example:
// Retrieved together with their responses
let otherResponseId;
let userInfoResponseId;
axios.get('url', {
cache: {
update: {
// Evict the otherRequestId cache when this response arrives
[otherResponseId]: 'delete',
// An example that update the "user info response cache" when doing a login.
// Imagine this request is a login one.
[userInfoResponseId]: (cachedValue, thisResponse) => {
return { ...cachedValue, user: thisResponse.user.info };
}
}
}
});
If the request should handle ETag
and If-None-Match support
. Use a string to force a
custom static value or true to use the previous response ETag. To use true
(automatic
etag handling), interpretHeader
option must be set to true
. Default: false
Use If-Modified-Since
header in this request. Use a date to force a custom static value
or true to use the last cached timestamp. If never cached before, the header is not set.
If interpretHeader
is set and a Last-Modified
header is sent then value from that
header is used, otherwise cache creation timestamp will be sent in If-Modified-Since
.
Default: true
Licensed under the MIT. See LICENSE
for more informations.
See my contact information on my github profile or open a new issue.
FAQs
Cache interceptor for axios
The npm package axios-cache-interceptor receives a total of 72,717 weekly downloads. As such, axios-cache-interceptor popularity was classified as popular.
We found that axios-cache-interceptor demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.