Skip to content

Commit 2d54240

Browse files
committed
refactor(Composables): Implement cache until function and replace it in posts manually caching
1 parent 927cf65 commit 2d54240

File tree

2 files changed

+30
-14
lines changed

2 files changed

+30
-14
lines changed

src/composables/cache.composable.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import StorageService from "@/services/storage.service";
2+
3+
export default function useLocaleStorageCache() {
4+
const getCache = (key) => {
5+
return StorageService.get(key);
6+
};
7+
const clearCache = (key) => StorageService.delete(key);
8+
9+
const setCache = (key, value) => StorageService.set(key, value);
10+
11+
return {
12+
getCache,
13+
clearCache,
14+
setCache,
15+
};
16+
}

src/composables/posts.composable.js

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,31 @@
11
import { ref } from "vue";
22
import { useLoading } from "./loading.composable";
33
import PostsServices from "@/services/posts.services";
4-
import StorageService from "@/services/storage.service";
4+
import useLocaleStorageCache from "./cache.composable";
55

66
export default function useFetchPost() {
77
const { endLoading, isLoading, startLoading } = useLoading();
8+
const { getCache, setCache } = useLocaleStorageCache();
89

910
const post = ref(null);
1011

11-
async function fetchPost (id) {
12-
const cachedPosts = StorageService.get("cached-posts") || {};
12+
async function fetchPost(id) {
13+
const cachedPosts = getCache("cached-posts") || {};
1314

1415
if (cachedPosts[`post-${id}`]) {
1516
post.value = cachedPosts[`post-${id}`];
16-
return
17-
}
18-
else{
17+
return;
18+
} else {
1919
startLoading();
2020
return PostsServices.getOneById(id)
21-
.then((response) => {
22-
post.value = response.data;
23-
StorageService.set('cached-posts', { ...cachedPosts, [`post-${id}`]: response.data })
24-
return response;
25-
})
26-
.finally(() => {
27-
endLoading();
28-
});
21+
.then((response) => {
22+
post.value = response.data;
23+
setCache('cached-posts', { ...cachedPosts, [`post-${id}`]: response.data })
24+
return response;
25+
})
26+
.finally(() => {
27+
endLoading();
28+
});
2929
}
3030
}
3131

0 commit comments

Comments
 (0)