Skip to content

Commit 8ed1ea2

Browse files
Update cacheApiCall.js
1 parent 8b1dfae commit 8ed1ea2

File tree

1 file changed

+48
-30
lines changed

1 file changed

+48
-30
lines changed

Interview Question/cacheApiCall.js

Lines changed: 48 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,59 @@
11
const cacheApiCall = (time) => {
2-
const cache = {};
3-
4-
return async (url, config = {}) => {
5-
const key = `${url}-${JSON.stringify(config)}`;
6-
const entry = cache[key];
7-
8-
if (!entry || Date.now() > entry.expiry) {
9-
try {
10-
console.log("Making new API call");
11-
const response = await fetch(url, config).then((res) =>
12-
res.json()
13-
);
14-
cache[key] = { value: response, expiry: Date.now() + time };
15-
} catch (err) {
16-
console.log(err);
17-
}
18-
}
19-
20-
return cache[key].value;
21-
};
2+
const cache = {};
3+
4+
return async (url, config = {}) => {
5+
const key = `${url}-${JSON.stringify(config)}`;
6+
const entry = cache[key];
7+
8+
// Check if entry exists and is not expired
9+
if (!entry || Date.now() > entry.expiry) {
10+
try {
11+
console.log("Making new API call");
12+
const response = await fetch(url, config).then((res) => res.json());
13+
14+
// Cache the response with an expiration time
15+
cache[key] = { value: response, expiry: Date.now() + time };
16+
17+
// Set a timeout to delete the cache after it expires
18+
setTimeout(() => {
19+
if (Date.now() > cache[key]?.expiry) {
20+
delete cache[key];
21+
console.log(`Cache expired and removed for key: ${key}`);
22+
}
23+
}, time);
24+
} catch (err) {
25+
console.error("API call failed:", err);
26+
}
27+
}
28+
29+
// Return the cached value
30+
return cache[key]?.value;
31+
};
2232
};
2333

34+
// Usage example
2435
const call = cacheApiCall(1500);
2536
call("https://jsonplaceholder.typicode.com/todos/1").then((data) =>
26-
console.log(data)
37+
console.log(data)
2738
);
2839

2940
setTimeout(() => {
30-
// Return data from cahce
31-
call("https://jsonplaceholder.typicode.com/todos/1").then((data) =>
32-
console.log(data)
33-
);
41+
// Returns data from cache if within cache time
42+
call("https://jsonplaceholder.typicode.com/todos/1").then((data) =>
43+
console.log(data)
44+
);
3445
}, 1000);
3546

3647
setTimeout(() => {
37-
// Making new API call
38-
call("https://jsonplaceholder.typicode.com/todos/1").then((data) =>
39-
console.log(data)
40-
);
41-
}, 2000);
48+
// Makes a new API call after cache expires
49+
call("https://jsonplaceholder.typicode.com/todos/1").then((data) =>
50+
console.log(data)
51+
);
52+
}, 4000);
53+
54+
setTimeout(() => {
55+
// Returns data from cache if within cache time
56+
call("https://jsonplaceholder.typicode.com/todos/1").then((data) =>
57+
console.log(data)
58+
);
59+
}, 5000);

0 commit comments

Comments
 (0)