Advertisement
crutch12

Untitled

Apr 28th, 2020
651
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { setupCache, serializeQuery } from 'axios-cache-adapter';
  2.  
  3. const cache = new LRU(/*...*/);
  4.  
  5. export default function({ $axios, store, isDev }) {
  6.   // https://github.com/RasCarlito/axios-cache-adapter/blob/98415a2d872954562c36df31a96b64427bbb2e4f/src/memory.js
  7.   class LruStore {
  8.     constructor() {
  9.       this.state = cache;
  10.     }
  11.  
  12.     getItem(key) {
  13.       const item = this.state.get(key) || null;
  14.       return item;
  15.     }
  16.  
  17.     setItem(key, value) {
  18.       if (!value.expires) return;
  19.       return this.state.set(key, value.data, value.expires - Date.now());
  20.     }
  21.  
  22.     removeItem(key) {
  23.       return this.state.del(key);
  24.     }
  25.  
  26.     clear() {
  27.       this.state.reset();
  28.     }
  29.  
  30.     length() {
  31.       return _.size(this.state);
  32.     }
  33.  
  34.     iterate(fn) {
  35.       return this.state.forEach(fn);
  36.     }
  37.   }
  38.  
  39.   let axiosCache = setupCache({
  40.     store: new LruStore(),
  41.     readHeaders: true,
  42.     key: req => req.url + (_.last(req.url) == '/' ? '' : '/') + serializeQuery(req),
  43.     exclude: {
  44.       query: false, // не игнорируем query в запросе
  45.       filter(req) {
  46.         return false; // по умолчанию всё пишем в кэш
  47.       },
  48.     },
  49.   });
  50.  
  51.   const defaults = $axios.defaults;
  52.   defaults.adapter = axiosCache.adapter;
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement