Last active
July 20, 2024 15:54
-
-
Save satyam4p/40568b6c00f7275961e4a81dd1c7f89b to your computer and use it in GitHub Desktop.
Implement a function that caches the API response for given expiry time if new call is made between the expiry time then return cached result else make new 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
//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]; | |
//check if cache has the key or the cache has expired for specific entry | |
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 }; //save the result in cache | |
} catch (error) { | |
console.error("An error occured while making the api call"); | |
} | |
} | |
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