Skip to content

Commit 9af5a55

Browse files
committed
feat: cache clean on searchs
1 parent dddf54f commit 9af5a55

File tree

1 file changed

+38
-6
lines changed

1 file changed

+38
-6
lines changed

src/api/cache.ts

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,51 @@
11
import { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
22
import qs from 'qs';
33

4+
const defaultTtl: number = 1000 * 60 * 5;
5+
6+
function log(...args: any[]) {
7+
if (import.meta.env.DEV) {
8+
console.log(`${new Date().toISOString()}`, ...args);
9+
}
10+
}
11+
12+
function checkCacheHasExpired(
13+
timestamp: number,
14+
ttl: number = defaultTtl
15+
): boolean {
16+
return new Date().getTime() - timestamp >= ttl;
17+
}
18+
19+
function clearExpiredCache() {
20+
log('cache - checando caches expirados...');
21+
Object.keys(localStorage)
22+
.filter((key: string) => key.startsWith('cache:'))
23+
.forEach((key) => {
24+
const data = localStorage.getItem(key);
25+
if (data) {
26+
const { timestamp } = JSON.parse(data);
27+
if (checkCacheHasExpired(timestamp)) {
28+
localStorage.removeItem(key);
29+
}
30+
}
31+
});
32+
}
33+
434
function getCacheRequestData(config: InternalAxiosRequestConfig<any>) {
535
if (
636
config.method === 'get' &&
737
config.url &&
838
config.headers['x-app-cache'] === 'true'
939
) {
10-
const url = config.url + '?' + qs.stringify(config.params);
40+
const url = 'cache:' + config.url + '?' + qs.stringify(config.params);
1141
const cache = localStorage.getItem(url);
1242
if (cache) {
1343
const { data, timestamp } = JSON.parse(cache);
14-
const ttl = 1000 * 60 * 5; // 5 minutes
15-
if (new Date().getTime() - timestamp >= ttl) {
16-
console.log(`cache - expirado - ${url}`);
44+
if (checkCacheHasExpired(timestamp)) {
45+
log(`cache - expirado - ${url}`);
1746
localStorage.removeItem(url);
1847
} else {
19-
console.log(`cache - ok - ${url}`);
48+
log(`cache - ok - ${url}`);
2049
return data;
2150
}
2251
}
@@ -25,7 +54,8 @@ function getCacheRequestData(config: InternalAxiosRequestConfig<any>) {
2554
}
2655

2756
function handleCacheResponse(resp: AxiosResponse<any, any>) {
28-
const url = resp.config.url + '?' + qs.stringify(resp.config.params);
57+
const url =
58+
'cache:' + resp.config.url + '?' + qs.stringify(resp.config.params);
2959
if (
3060
resp.config.method === 'get' &&
3161
resp.config.url &&
@@ -44,4 +74,6 @@ function handleCacheResponse(resp: AxiosResponse<any, any>) {
4474
}
4575
}
4676

77+
clearExpiredCache();
78+
4779
export { handleCacheResponse, getCacheRequestData };

0 commit comments

Comments
 (0)