Description

APIs can be slow or unreliable. To improve performance, we can cache API responses, but sometimes the API may fail.

In this challenge, you’ll create an async cache wrapper that:

  1. Returns cached data if the same request is repeated.
  2. Handles API errors gracefully.
  3. Supports await for async functions.
  4. Expires cached results after a specified time.

Task

Implement a function cachedApi(timer) that returns an async function:

  • Parameters
    • url → API endpoint
    • options → fetch options
  • Behavior
    1. If the URL is in the cache, return cached data immediately.
    2. If not, call fetch(url, options) and cache the JSON response.
    3. If fetch fails, throw the error to the caller.
    4. After timer milliseconds, remove the cache entry so a fresh call can happen.

Example Usage

const api = cachedApi(1000); // cache expires in 1 second

// First call → fetches from API
const data1 = await api("https://api.example.com/data");

// Second call (within 1s) → returns cached data
const data2 = await api("https://api.example.com/data");

// After 1 second → cache expires, next call fetches fresh data
setTimeout(async () => {
const data3 = await api("https://api.example.com/data");
}, 1100);

Hints

Hint 1

Use a Map or object to store cached responses.

Hint 2

Wrap the fetch call in a try/catch to handle errors.