-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCachedApi.js
More file actions
41 lines (36 loc) · 952 Bytes
/
CachedApi.js
File metadata and controls
41 lines (36 loc) · 952 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
async function fetchResponse(url) {
const res = await fetch(url);
const jsonResponse = await res.json();
return jsonResponse;
}
function cachedApiCall(time) {
let apiData = new Map();
return async function (url) {
if (apiData.has(url)) {
const res = apiData.get(url);
if (Date.now() - res.timeStamp <= time) {
return Promise.resolve(res.value);
}
}
const makeApiCall = await fetchResponse(url);
apiData.set(url, {
value: makeApiCall,
timeStamp: Date.now(),
});
return Promise.resolve(makeApiCall);
};
}
const call = cachedApiCall(1500);
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((a) =>
console.log(a)
);
setTimeout(() => {
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((a) =>
console.log(a)
);
}, 700);
setTimeout(() => {
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((a) =>
console.log(a)
);
}, 2000);