Caching adapter for axios.
- Support
localStorage
、sessionStorage
、memory
mode - Support each request to be configured
- Rerequest when the request parameter is inconsistent with the last request parameter
Using npm:
npm install axios-storage --save
Using cdn:
<script src="https://unpkg.com/axios-storage/dist/axios-storage.js"></script>
You can use the axios-storage directly
import axios from 'axios';
import AxiosStorage from 'axios-storage';
// set global config
AxiosStorage.config({
storagePrefix: 'axios-storage',
storageMode: 'sessionStorage',
maxAge: 120 * 60 * 1000
});
const api = axios.create({
adapter: AxiosStorage.adapter
});
api({
method: 'get',
url: '/data',
cacheConfig: {
maxAge: 60 * 60 * 1000,
storageMode: 'sessionStorage'
}
})
.then(function(res){
console.log(res);
})
api({
method: 'get',
url: '/data/other',
cacheConfig: {
maxAge: 60 * 60 * 1000,
storageMode: 'localStorage'
}
})
.then(function(res){
console.log(res);
})
// or use global config
api({
method: 'get',
url: '/data/other',
cacheConfig: true
})
.then(function(res){
console.log(res);
})
global config options, see all options
Param | Type | Default | Description |
---|---|---|---|
options | object |
||
[options.storagePrefix] | string |
"axios-storage" |
thhe prefix of storage |
[options.storageMode] | string |
"sessionStorage" |
the mode of storage,support localStorage 、sessionStorage 、memory |
[options.deleteOnExpire] | string |
"aggressive" |
how to handler expired storage |
Example
import axios from 'axios';
import AxiosStorage from 'axios-storage';
AxiosStorage.config({
storagePrefix: 'axios-storage-example:',
storageMode: 'sessionStorage'
});
adapter
Example
import axios from 'axios';
import AxiosStorage from 'axios-storage';
const api = axios.create({
adapter: AxiosStorage.adapter
});
api.get(...)
api.post(...)
Cache Object
Returns: object
- Cache,see detail Cache
Param | Type | Default | Description |
---|---|---|---|
options | object | string |
||
[options.storageMode] | string |
"sessionStorage" |
storage mode |
Example
let oCache = AxiosStorage.getCache('localStorage');
oCache.put('foo', 'bar');
oCache.get('foo'); // "bar"
...
// request data with cacheConfig
api({
method: 'GET',
url: '/data/other',
cacheConfig: {
maxAge: 60 * 60 * 1000,
storageMode: 'localStorage'
}
})
.then((res) => {
console.log(res)
})
// get this request cache
let res = oCache.get('GET./data/other') // `res` is the same as above
oCache.get('[method].[url]') // `method` is uppercase, GET、POST etc.
cd example && npm install
node app.js
after that,browser open http://localhost:3000/