리팩토링 / 부산에 가면 6. CacheStorage

이창훈·2023년 1월 10일
1

부산에가면

목록 보기
10/11
post-thumbnail

코드바로가기

import axios from "axios"

export const getRestaurantInfo = async() => {
  const ServiceKey = decodeURIComponent(process.env.REACT_APP_SERVICE_KEY)
  if('caches' in window){
    const cacheStorage = await caches.open('restaurant')
    const cachedResponse = await cacheStorage.match('restaurant')
    if(!cachedResponse || !cachedResponse.ok){
      const response = await axios.get('https://apis.data.go.kr/6260000/FoodService/getFoodKr?',
      {
        params :
        {
            resultType : 'json',
            numOfRows : '149',
            serviceKey : ServiceKey
        }
    })
    const data = response.data.getFoodKr.item
    console.log(data, 'cacheStarage에 데이터가 없어서 새로 받아왔습니다')
    cacheStorage.put('restaurant', new Response(JSON.stringify(data)))
      return data
    }
    const cached = await cachedResponse?.json()
    console.log(cached, '데이터가 있어서 cacheStarage에 있는 걸 드립니다!')
    return cached
  }
  return []
}

1. const cacheStorage = await caches.open('restaurant')

캐시를 열려면 caches.open(name) 메서드를 사용하여 캐시 이름을 단일 매개 변수로 전달한다.
명명된 캐시가 없으면 생성된다. 이 메서드는 Cache개체로 처리되는 Promise를 반환한다.

2. const cachedResponse = await cacheStorage.match('restaurant')

캐시에서 항목을 찾으려면 match메서드를 사용할 수 있다.
일치하는 항목이 발견되면 Promise를 반환한다.
일치하는 항목을 발견할 수 없으면 undefined를 반환한다.

test를 키로 하는 값이 없기 때문에 undefined를 반환했고
restaurant를 키로 하는 값이 있기 때문에 Promise 반환했고 ok프로퍼티true가 담겨있다.

3. cacheStorage.put('restaurant', new Response(JSON.stringify(data)))

.put(req, res)메서드는 네트워크로부터의 응답을 저장하거나 자신의 Response를 생성 및 저장할 수 있다.

첫 번째 파라미터는 객체 또는 URL일 수 있으며
두번 째 파라미터는 생성된 Response여야 한다.

정리 :
case 1.
'restaurant'을 키로 갖는 cache저장소에 'restaurant'를 키로 갖는 cache 값이 없거나, 'restaurant'키를 갖는 값이 falsy한 값이 아닐 경우(undefined, 혹은 .ok프로퍼티의 값이 false) 즉, 'restaurant'의 값이 없을 경우에 식당 데이터를 fetch해와서
키 값이'restaurant'인 cacheStorage에 'restaurant'키 값으로 fetch한 데이터를 저장한다.

case 2.
restaurant'을 키로 갖는 cache저장소에 'restaurant'를 키로 갖는 cache 값이 있거나, 'restaurant'키를 갖는 값이 truly할 경우,
새로 데이터를 fetch하지 않고
키 값이 'restaurant'인 cacheStorage에 'restaurant'키 값으로 저장 되어있는 데이터 정보를 그냥 가져온다.

profile
실패를 두려워하지 않고 배우고 기록하여 내일의 밑거름 삼아 다음 단계로 성장하겠습니다.

0개의 댓글