캐싱은 종류에 따라 추적이 힘든 오류를 발생 시킬 수 있지만 이번에 소개한 캐싱 방법은 타 캐싱 방법에 비해 비교적 안전하게 도입 할 수 있습니다. cacahe key만 제대로 주어진다면 로딩없는 화면과 항상 최신에 데이터를 유지 할 수 있기 때문이에요.
async [CategoryActions.categorySelectFilterHttpCache]({ commit, state }: ActionContext<CategoryState, AppState>, payload: {categoryId: string; selectedFilter: CategoryFilter}) {
commit(CategoryMutations.SET_LOADING,true)
commit(CategoryMutations.SET_SELECTED_FILTER, payload.selectedFilter)
state.payload.categoryId = payload.categoryId
state.payload.paging = CategoryRepository.getDefaultCategoryPayload().paging
CategoryRepository.getCategorysCacheHitFirst(state.payload)
.subscribe( (categoryList) =>{
// 1call 당 2번 subscribe(1. cache, 2.response)
state.payload.paging.loadSize = categoryList.length
commit(CategoryMutations.SET_CATEGORY_LIST, categoryList)
commit(CategoryMutations.SET_LOADING, false)
}
)
},
/** 캐싱 데이터 선방출 후 응답 데이터 방출 */
getCategorysCacheHitFirst(payload: CategoryPayload): Observable<CategoryDTO[]>{
const cacheKey = this.cagegoryPayloadCacheKey(payload)
return new Observable<CategoryDTO[]>(subscriber => {
if(httpLruCache.has(cacheKey)){
subscriber.next(httpLruCache.get(cacheKey) as CategoryDTO[]) // Hit Cache 방출.1
}
const res = HttpService.get<CategoryDTO[]>('/posts');
res.then( response => {
const categoryList = this.toVM(payload.paging.start(), payload.paging.end(),response.data)
subscriber.next(categoryList) // Hit Response 방출.2
httpLruCache.set(cacheKey, categoryList)
subscriber.complete()
subscriber.unsubscribe()
})
res.catch(reason => {
subscriber.error(reason)
})
}
)
}