Dedupe concurrent identical API calls and cache responses
Implement a function that enhances a given API call function by merging identical calls and caching their responses to optimize network usage. This approach should prevent multiple identical requests from being sent to the server simultaneously, reducing unnecessary network traffic and load on the server. To merge identical API calls, you will work closely with Promises.
The function, createGetAPIWithMerging, takes an API call function getAPI as an argument and returns a new function. This new function behaves like getAPI but with added capabilities:
Usage Example:
const mergedGetAPI = createGetAPIWithMerging(getAPI);
const response1 = await mergedGetAPI('/data', { params: { id: 123 } });
const response2 = await mergedGetAPI('/data', { params: { id: 123 } }); // This call will be merged with the first one if made within 1 second.
Here, getAPI is the original function for making GET requests. createGetAPIWithMerging enhances it by caching and merging, ensuring that if multiple identical requests are made in rapid succession, only one will be sent to the server, and its response will be used for all of them.
The cache is automatically managed to contain only a limited number of recent responses and to expire entries after a short period, ensuring the data’s freshness and limiting memory usage.