feat(cache): implement caching of routes

This commit is contained in:
zyachel
2023-05-21 18:15:03 +05:30
parent 8599ae2c5a
commit c53c88db9b
9 changed files with 82 additions and 42 deletions

View File

@ -0,0 +1,4 @@
export const titleKey = (titleId: string) => `title:${titleId}`;
export const nameKey = (nameId: string) => `name:${nameId}`;
export const findKey = (query: string) => `find:${query}`;
export const mediaKey = (url: string) => `media:${url}`;

View File

@ -0,0 +1,24 @@
import redis from 'src/utils/redis';
const ttl = process.env.REDIS_CACHE_TTL_API ?? 30 * 60;
const redisEnabled =
process.env.USE_REDIS === 'true' || process.env.USE_REDIS_FOR_API_ONLY === 'true';
const getOrSetApiCache = async <T extends (...fetcherArgs: any[]) => Promise<any>>(
key: string,
fetcher: T,
...fetcherArgs: Parameters<T>
): Promise<ReturnType<T>> => {
if (!redisEnabled) return await fetcher(...fetcherArgs);
const dataInCache = await redis.get(key);
if (dataInCache) return JSON.parse(dataInCache);
const dataToCache = await fetcher(...fetcherArgs);
await redis.setex(key, ttl, JSON.stringify(dataToCache));
return dataToCache;
};
export default getOrSetApiCache;

View File

@ -2,7 +2,8 @@
import Redis from 'ioredis';
const redisUrl = process.env.REDIS_URL;
const toUseRedis = process.env.USE_REDIS === 'true';
const toUseRedis =
process.env.USE_REDIS === 'true' || process.env.USE_REDIS_FOR_API_ONLY === 'true';
const stub: Pick<Redis, 'get' | 'setex' | 'getBuffer'> = {
get: async key => Promise.resolve(null),