Created
July 20, 2020 14:51
-
-
Save rijkvanzanten/48e93db38e2563630ccb1ceac83b8a2f to your computer and use it in GitHub Desktop.
Axios w/ Cache Interceptors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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