Skip to content

Instantly share code, notes, and snippets.

@rijkvanzanten
Created July 20, 2020 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rijkvanzanten/48e93db38e2563630ccb1ceac83b8a2f to your computer and use it in GitHub Desktop.
Save rijkvanzanten/48e93db38e2563630ccb1ceac83b8a2f to your computer and use it in GitHub Desktop.
Axios w/ Cache Interceptors
const axios = require('axios');
const cache = require('memory-cache');
require('dotenv').config();
const api = new axios.create({
baseURL: process.env.API_URL,
headers: {
'Authorization': 'Bearer ' + process.env.API_TOKEN
}
});
api.interceptors.request.use(request => {
// We only want to cache get requests
if (request.method !== 'get') return request;
const cached = cache.get(request.url);
if (cached) {
request.adapter = () => Promise.resolve({
data: cached,
status: 200,
statusText: 'OK',
headers: request.headers,
config: request,
request: request
});
return request;
}
return request;
});
api.interceptors.response.use(response => {
if (response.config.method !== 'get') return response;
// Cache responses in memory for 5 minutes
cache.put(response.config.url, response.data, 5 * 60 * 1000);
return response;
});
module.exports = api;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment