Skip to content

Commit

Permalink
feat: trending API 호출 결과를 캐싱하기 위한 캐시 모듈 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
hwinkr committed Sep 9, 2024
1 parent 0ccfd1e commit 1939747
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/apis/gifAPIService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { GifsResult } from '@giphy/js-fetch-api';
import { IGif } from '@giphy/js-types';

import { GifImageModel } from '../models/image/gifImage';
import { apiClient, ApiError } from '../utils/apiClient';
import { apiClient, apiClientWithCache, ApiError } from '../utils/apiClient';

const API_KEY = process.env.GIPHY_API_KEY;
if (!API_KEY) {
Expand Down Expand Up @@ -43,7 +43,7 @@ export const gifAPIService = {
* @returns {Promise<GifImageModel[]>}
* @ref https://developers.giphy.com/docs/api/endpoint#!/gifs/trending
*/
getTrending: async (): Promise<GifImageModel[]> => {
getTrending(): Promise<GifImageModel[]> {
const url = apiClient.appendSearchParams(new URL(`${BASE_URL}/trending`), {
api_key: API_KEY,
limit: `${DEFAULT_FETCH_COUNT}`,
Expand All @@ -52,6 +52,14 @@ export const gifAPIService = {

return fetchGifs(url);
},

getTrendingWithCache: async () => {
return await apiClientWithCache({
queryKey: 'trending-gifs',
staleTime: 1000 * 60 * 5,
queryFn: gifAPIService.getTrending
});
},
/**
* 검색어에 맞는 gif 목록을 가져옵니다.
* @param {string} keyword
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Search/hooks/useGifSearch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const useGifSearch = () => {
if (status !== SEARCH_STATUS.BEFORE_SEARCH) return;

try {
const gifs = await gifAPIService.getTrending();
const gifs = await gifAPIService.getTrendingWithCache();
setGifList(gifs);
} catch (error) {
handleError(error);
Expand Down
23 changes: 23 additions & 0 deletions src/utils/apiClient.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import cache from './cache';

export class ApiError extends Error {
constructor(public status: number, message?: string) {
super(message);
Expand All @@ -22,3 +24,24 @@ export const apiClient = {
return newUrl;
}
};

interface ApiClientWithCacheArgs<T> {
queryFn: () => Promise<T>;
queryKey: string;
staleTime: number;
}

export const apiClientWithCache = async <T>({
queryFn,
queryKey,
staleTime
}: ApiClientWithCacheArgs<T>) => {
const cachedData = cache.get<T>(queryKey);

if (cachedData && cache.isValidCache(queryKey)) return cachedData;

const newData = await queryFn();
cache.set(queryKey, newData, staleTime);

return newData;
};
30 changes: 30 additions & 0 deletions src/utils/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
interface CacheItem<T> {
data: T;
expiredTime: number;
}

class Cache {
private cache: Record<string, CacheItem<any>> = {};

isValidCache(key: string): boolean {
const item = this.cache[key];
if (!item) return false;

return Date.now() <= item.expiredTime;
}

get<T>(key: string): T | null {
if (!this.cache[key]) return null;

return this.cache[key].data;
}

set<T>(key: string, data: T, ttl: number): void {
const expiredTime = Date.now() + ttl;
this.cache[key] = { data, expiredTime };
}
}

const cache = new Cache();

export default cache;

0 comments on commit 1939747

Please sign in to comment.