Skip to content

Instantly share code, notes, and snippets.

@ChangJoo-Park
Created March 6, 2021 00:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ChangJoo-Park/8bc5ce005797782cad179c0bce0f5245 to your computer and use it in GitHub Desktop.
Save ChangJoo-Park/8bc5ce005797782cad179c0bce0f5245 to your computer and use it in GitHub Desktop.
const fetcher = (url) => fetch(url).then(response => response.json())
const store = {}
const defaultPrefetchOption = {
ttl: 1000 * 10,
resetCache: false,
}
/**
*
* 사용법 :
*
* 조회 후 캐시를 10초간 보관 후 삭제합니다.
* ```js
* const options = { ttl: 1000 * 10, resetCache: false }
* const { data } = await usePrefetchStore('dashboard', /api/dashboard, options)
* ```
*
* 존재하는 캐시를 제거하고 서버 요청을 통해 다시 캐시를 설정하고 10초간 보관 후 삭제합니다.
* ```js
* const options = { ttl: 1000 * 10, resetCache: true }
* const { data } = await usePrefetchStore('dashboard', /api/dashboard, options)
* ```
*/
async function usePrefetchStore(key, url, options = {}) {
// 기본 설정을 전달받은 설정과 합합니다
const prefetchOptions = Object.assign({}, defaultPrefetchOption, options)
// true면 기존 캐시를 강제로 제거합니다
if (prefetchOptions.resetCache) {
clearCache(key)
}
// 캐시에 이미 존재한다면 캐시를 사용합니다.
if (store[key] && store[key].data) {
const cache = store[key]
return { data: cache.data, error: null }
}
try {
// fetch API 를 이용하여 원격 서버에 데이터를 요청합니다.
const data = await fetcher(url)
store[key] = { data, error: null }
// 요청이 완료되면 옵션의 `ttl` 이후에 삭제합니다.
setTimeout(() => {
clearCache(key)
}, prefetchOptions.ttl);
return { data, error: null }
} catch (error) {
// 요청에 에러가 있으면 에러를 리턴합니다.
return { data: null, error }
}
}
function clearCache(key) {
if (store.hasOwnProperty(key)) {
delete store[key]
}
if (!key) {
store = {}
}
}
export default usePrefetchStore
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment