Exercise 11: Fetch with Request Interceptor

Problem Statement

Function `fetchWithInterceptor(url, options, interceptor)` banao jo request ko intercept kare before sending. Example: fetchWithInterceptor(url, {}, (req) => {req.headers.set("X-Custom", "value")})

Sample Output:

await fetchWithInterceptor(url, {}, (req) => req.headers.set("X-Custom", "value"))
// Intercepts and modifies request

Solution

const fetchWithInterceptor = async (url, options = {}, interceptor) => {
  const request = new Request(url, options);
  if (interceptor) interceptor(request);
  return fetch(request);
};

Explanation

Overall Goal:

  • Request ko intercept karna before sending.

Real world:

  • Request modification: header injection.
  • Middleware: request transformation.