axios-extensions - 1.cacheAdapterEnhancer

Aneb·2023년 3월 29일
0

Installing

yarn add axios-extensions

Usage

import axios from 'axios';
import { cacheAdapterEnhancer, throttleAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
	baseURL: '/',
	headers: { 'Cache-Control': 'no-cache' },
	adapter: throttleAdapterEnhancer(cacheAdapterEnhancer(axios.defaults.adapter))
});

throttle과 enhancer 를 사용하여 original axios adapter를 쉽게 컨트롤할 수 있습니다.


1. cacheAdapterEnhancer

axios의 캐시 처리에 대한 옵션을 제공합니다.

options

ParamTypeDefault valueDescription
enabledByDefaultbooleantrue요청 구성에 명시적으로 정의되지 않은 모든 요청에 대해 캐싱합니다.
cacheFlagstring'cache'axios 요청에서 캐시 사용량을 명시적으로 정의하기 위한 키(플래그)를 구성합니다
defaultCacheCacheLikenew LRUCache({ maxAge: FIVE_MINUTES, max: 100 })기본적으로 요청을 저장하는 데 사용되는 CacheLike instance (config로 사용자 지정 캐시를 정의하는 경우 제외)

usage

import axios from 'axios';
import { cacheAdapterEnhancer } from 'axios-extensions';

const http = axios.create({
	baseURL: '/',
	headers: { 'Cache-Control': 'no-cache' },
	// cache will be enabled by default
	adapter: cacheAdapterEnhancer(axios.defaults.adapter)
});

http.get('/users'); // http 요청 호출
http.get('/users'); // 실제 http 요청 없이 이전 요청의 캐시에서 응답 사용
http.get('/users', { cache: false }); //수동으로 캐시를 비활성화하고 실제 http 요청이 호출 

custom cache flag


const http = axios.create({
	baseURL: '/',
	headers: { 'Cache-Control': 'no-cache' },
	// enabledByDefault를 false로 설정하고, cacheFlag를 설정
	adapter: cacheAdapterEnhancer(axios.defaults.adapter, { enabledByDefault: false, cacheFlag: 'useCache'})
});

http.get('/users'); // 캐싱이 불가능한 http 요청 호출
http.get('/users', { useCache: true }); // 캐싱이 가능한 http 요청 호출
http.get('/users', { useCache: true }); // 이전 요청의 응답 캐시 사용

+with typescript

custom cache flag와 typescript를 함께 사용한다면, 다음과 같은 설정이 필요합니다.

import { ICacheLike } from 'axios-extensions';
declare module 'axios' {
  interface AxiosRequestConfig {
    // if your cacheFlag was setting to 'useCache'
    useCache?: boolean | ICacheLike<any>;
  }
}

more advanced

AdapterEnhancer를 통해 요청을 구성하는 것 외에도, 모든 개별 요청을 구성하여 보다 고급 기능을 사용할 수 있습니다.

import axios from 'axios';
import { cacheAdapterEnhancer, Cache } from 'axios-extensions';

const http = axios.create({
	baseURL: '/',
	headers: { 'Cache-Control': 'no-cache' },
	adapter: cacheAdapterEnhancer(axios.defaults.adapter, { enabledByDefault: false })
});

http.get('/users', { cache: true });

// 직접 캐시 정의
const cacheA = new Cache();
// or 캐시와 유사한 인스턴스 정의
const cacheB = { get() {/*...*/}, set() {/*...*/}, del() {/*...*/} };

// 서로 다른 캐시이기 때문에 두 개의 요청이 이루어집니다.
http.get('/users', { cache: cacheA });
http.get('/users', { cache: cacheB });

// forceUpdate가 true이기 때문에 캐시된 http요청이 호출됩니다.
http.get('/users', { cache: cacheA, forceUpdate: true });
profile
FE Developer

0개의 댓글