Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created July 20, 2024 15:49
Show Gist options
  • Save satyam4p/e1c8e34930bd78f7c4c982f4013d243b to your computer and use it in GitHub Desktop.
Save satyam4p/e1c8e34930bd78f7c4c982f4013d243b to your computer and use it in GitHub Desktop.
//Problem Statement
//Implement a function in JavaScript that caches the API response for the given amount of time.
//If a new call is made between that time, the response from the cache will be returned,
//else a fresh API call will be made.
/**
*
* @param {*} expiryTime in ms
*/
function cachedApi(expiryTime) {
let cache = {};
return async function (path, config = {}) {
const key = generatekey(path, config);
let entry = cache[key];
console.log(Date.now());
console.log("expiry time:: ", entry?.expiryTime);
if (!entry || Date.now() > entry.expiryTime) {
console.log("making new api call");
try {
let response = await fetch(path, config);
let result = response.json();
cache[key] = { result, expiryTime: Date.now() + expiryTime };
} catch (error) {
console.error("An error occured while making the api call");
}
}
// console.log("cache:: ", cache);
return cache[key].result;
};
}
/**
* generate unique key for each api call
* @param {*} path
* @param {*} config
* @returns
*/
function generatekey(path, config) {
const key = Object.keys(config)
.sort((a, b) => a.localeCompare(b))
.map((k) => k + ":" + config[k].toString())
.join("&");
return path + key;
}
//usage
let call = cachedApi(3000);
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((res) =>
console.log(res)
);
setTimeout(() => {
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((res) =>
console.log(res)
);
}, 700);
setTimeout(() => {
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((res) =>
console.log(res)
);
}, 2000);
setTimeout(() => {
call("https://jsonplaceholder.typicode.com/todos/1", {}).then((res) =>
console.log(res)
);
}, 5000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment