axios cashe in typescript

Axios allows you to cache responses by adding an adapter to your configuration. You can use a library like axios-cache-adapter to cache responses using Axios in Typescript. Here's an example:

index.ts
import axios, { AxiosInstance } from 'axios';
import * as adapter from 'axios-cache-adapter';

const cache = adapter.setupCache({
  maxAge: 15 * 60 * 1000 // cache for 15 minutes
});

const api: AxiosInstance = axios.create({
  adapter: cache.adapter
});

api.interceptors.request.use((config) => {
  const key = `${config.method}|${config.url}`;

  // add a custom cache key to prevent cache clashes
  config.params = config.params || {};
  config.params.__cacheKey = key;

  return config;
});

export default api;
517 chars
23 lines

The code above creates an Axios instance with a cached adapter from axios-cache-adapter. The cache.adapter is then added as the adapter to the Axios instance. This allows all requests made through this instance to be cached.

The api instance then adds an interceptor to include a __cacheKey parameter in the request URL to differentiate between multiple requests with the same URL but different parameters. This allows Axios to cache the responses separately for each request.

With this setup, you can simply use the api instance to make requests, and Axios will cache responses automatically. For example:

index.ts
async function getUsers(): Promise<User[]> {
  const response = await api.get('/users');
  return response.data;
}
115 chars
5 lines

This example uses the api instance to make a GET request to /users. The response is automatically cached by Axios and subsequent requests to the same endpoint will return the cached response if it's still valid.

Note that caching can have unintended consequences, like showing stale data or users experiencing different data when hitting the same endpoint with different query parameters. You should use caching cautiously and only where it makes sense.

gistlibby LogSnag