Skip to content

Instantly share code, notes, and snippets.

@ankitbtanna
Created November 13, 2023 14:37
Show Gist options
  • Save ankitbtanna/e8d4a2acefc7be5d5376f271be46302c to your computer and use it in GitHub Desktop.
Save ankitbtanna/e8d4a2acefc7be5d5376f271be46302c to your computer and use it in GitHub Desktop.
Atlassian Frontend Software Interview - Cached API call
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