Created
November 13, 2023 14:37
-
-
Save ankitbtanna/e8d4a2acefc7be5d5376f271be46302c to your computer and use it in GitHub Desktop.
Atlassian Frontend Software Interview - Cached API call
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cachedApiCall = (time) => { | |
const cache = {}; | |
return async (url, config = {}) => { | |
const key = `${url}${JSON.stringify(config)}`; | |
const entry = cache[key]; | |
if(!entry || Date.now() > entry.expiry){ | |
try{ | |
console.log("Making a fresh api call"); | |
let resp = await fetch(url, config); | |
resp = await resp.json(); | |
cache[key] = {value: resp, expiry: Date.now() + time}; | |
return cache[key].value; | |
}catch(e){ | |
console.log("error while making api call", JSON.stringify(e)); | |
} | |
} else { | |
console.log("Returning from cache"); | |
return cache[key].value; | |
} | |
} | |
} | |
const call = cachedApiCall(5000); | |
call('https://jsonplaceholder.typicode.com/todos/1', {}).then((a) => console.log("1", a)); | |
setTimeout(() => { | |
call('https://jsonplaceholder.typicode.com/todos/1', {}).then((a) => console.log("2", a)); | |
}, 2000); | |
setTimeout(() => { | |
call('https://jsonplaceholder.typicode.com/todos/1', {}).then((a) => console.log("3", a)); | |
}, 4000); | |
setTimeout(() => { | |
call('https://jsonplaceholder.typicode.com/todos/1', {}).then((a) => console.log("4", a)); | |
}, 6000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment