@tictactrip/axios-redis
v4.0.0
Published
Axios Redis cache middleware
Downloads
2,808
Readme
axios-redis
Description
This repository provides a smart and powerful Axios Redis cache adapter. Cached data is compressed with zlib and Brotli.
Install
yarn add @tictactrip/axios-redis
Example
import * as redis from 'redis';
import axios from 'axios';
import { AxiosRedis } from '@tictactrip/axios-redis';
// Redis connexion
const redis = redisClient.createClient({ host: 'localhost' });
// Create your AxiosRedis instance (config parameter is optional)
const axiosRedis = new AxiosRedis(redis, {
expirationInMS: 30000,
separator: '___',
prefix: '@tictactrip/axios-redis',
axiosConfigPaths: ['method', 'url', 'params', 'data'],
});
// Create your Axios instance
const axiosInstance = axios.create({
baseURL: 'http://api.example.com',
adapter: (config) => AxiosRedis.ADAPTER(config, axiosRedis),
});
// Response will be cached on first call
await axiosInstance.get('/user?ID=12345');
// On second call, if response is still cached, adapter returns cached response without sending the request
await axiosInstance.get('/user?ID=12345');
HTTP methods cached
As default, all GET and POST responses are cached. If you want to customize them, you can also do:
axiosRedis.methodsToCache = [EHttpMethod.GET];
Key structure
By default, redis keys follow this pattern
{prefix}___{http_method}___{axios_config_url}___base64{axios_config_params}___base64{axios_config_data}
Example:
@scope/[email protected]___["post"]___WyIvZXhhbXBsZTE/cGFyYW0xPXRydWUmcGFyYW0yPTEyMyJd___W10=___WyJ7XCJoZWxsb1wiOlwid29ybGRcIn0iXQ==
If you want to customize the keys, you just need to customize your AxiosRedis
instance.
Disable cache for one request
// This request won't be cached
await axiosInstance.get('/user?ID=12345', {
headers: {
'Axios-Redis-Cache-Duration': null,
},
});
Customize cache duration for one request
// This request will be cached during 90000ms
await axiosInstance.get('/user?ID=12345', {
headers: {
'Axios-Redis-Cache-Duration': 90000,
},
});
Tests
How can I mock Redis connection with Jest in my unit tests?
import * as redis from 'redis';
import { AxiosRedis } from '@tictactrip/axios-redis';
describe('Example', () => {
it('should send the request without a redis connection', () => {
const redisClient = redis.createClient({ retry_strategy: jest.fn() });
const axiosRedisSpy = jest.spyOn(AxiosRedis.prototype, 'getCache')
.mockRejectedValue(new Error('Bypass Redis for tests'));
// ...
});
});
Scripts
Run using yarn run <script>
command.
clean - Remove temporarily folders.
build - Compile source files.
build:watch - Interactive watch mode, compile sources on change.
lint - Lint source files.
lint:fix - Fix lint source files.
test - Runs all tests with coverage.
License
GPL-3.0 © Tictactrip