Skip to curriculum
Jump to the editor

24.9. An API client with interceptors and typed errors

Medium
Topics

This question is in

24. Build a small library
40–60 min

Most apps wrap fetch in a small API client. Every request then shares one base URL, default headers and JSON handling, and two hooks run around it: request interceptors (add an auth token, a trace id) and response interceptors (unwrap an envelope, log timing). The client also gives failures a type: a server that answered 404 is an HttpError with its status and body, and a request that never got an answer is a NetworkError. That lets calling code write if (error instanceof HttpError && error.status === 404) instead of parsing messages.

Write the error classes and createClient(options) in client.js.

Signature

JAVASCRIPT
class ApiError extends Error      // error.config
class HttpError extends ApiError  // error.status, error.data, error.response
class NetworkError extends ApiError // error.cause

function createClient({ baseURL, headers }) // both optional; returns the client

client.request({ method, path, params, body, headers })  // returns a promise of the response
client.get(path, options)          client.delete(path, options)
client.post(path, body, options)   client.put(path, body, options)
client.useRequest(fn)    // fn(config) returns the config (or a promise of it)
client.useResponse(fn)   // fn(response) returns the response (or a promise of it)
// both return a function that removes the interceptor

// config:   { method, url, headers, body }
// response: { status, headers, data, config }

options in the helpers takes the same keys as request (params, headers), and the helper sets method, path and body.

Requirements

  1. The URL is baseURL and path joined with exactly one /. A path that starts with http:// or https:// is used as it is, and without baseURL the path is used as it is.
  2. params is added as a query string built with URLSearchParams: an array adds one pair per item, and undefined and null values are left out. It is joined with ?, or with & when the path already has a query, and it goes before any #fragment, which stays at the end ("/docs#intro" → /docs?a=1#intro).
  3. The method is upper-cased; request without one uses GET.
  4. Headers are the client's headers merged with the request's, with every name in lower case; the request's value wins. Each request gets its own new headers object.
  5. Request interceptors run in the order they were added, each awaited, each receiving the config returned by the one before. config.body is still the value passed in. A request interceptor that throws or rejects fails the request, and fetch is not called.
  6. After the interceptors, the client calls the global fetch(config.url, init) once, where init is { method, headers } plus body when there is one. A string body is sent as it is; any other body is sent as JSON.stringify(body), with content-type: application/json added unless a content-type is already set.
  7. The response's body is read as text. An empty body (a 204, for example) gives data null; a content-type containing application/json gives the parsed JSON; anything else gives the text. The result is { status, headers, data, config }, where headers is the Response's Headers object.
  8. A status outside 200–299 rejects with an HttpError (message Request failed with status <status>) carrying status, data, response and config. For such a response, a body that is not valid JSON is kept as text in data.
  9. A successful response whose JSON is invalid rejects with an ApiError (message Invalid JSON response), not an HttpError.
  10. When fetch itself throws or rejects, the request rejects with a NetworkError (message Network error: <the cause's message>), with cause set to what fetch threw and config set.
  11. Each error's name is its class name. HttpError and NetworkError are instances of ApiError and of Error.
  12. Response interceptors run in order, awaited, only for successful responses (after data is read); the request resolves to what the last one returns.
  13. An interceptor that returns something that is not an object rejects the request with a TypeError: A request interceptor must return the config or A response interceptor must return the response.
  14. The function returned by useRequest or useResponse removes exactly that interceptor; calling it again does nothing. Passing a non-function throws a TypeError with the message An interceptor must be a function. Two clients never share interceptors.

Examples

JAVASCRIPT
const api = createClient({ baseURL: "https://api.example.com/v1", headers: { Accept: "application/json" } });

api.useRequest((config) => ({ ...config, headers: { ...config.headers, authorization: "Bearer abc" } }));
api.useResponse((response) => ({ ...response, data: response.data.result }));

const response = await api.get("/users", { params: { page: 2, tag: ["new", "vip"] } });
// fetch("https://api.example.com/v1/users?page=2&tag=new&tag=vip",
//       { method: "GET", headers: { accept: "application/json", authorization: "Bearer abc" } })
// the server answers { "result": [...] }, so response.data is that array
JAVASCRIPT
await api.post("/users", { name: "Ada" });
// fetch(…/users, { method: "POST",
//   headers: { accept: "application/json", authorization: "Bearer abc", "content-type": "application/json" },
//   body: '{"name":"Ada"}' })
JAVASCRIPT
try {
  await api.get("/users/999");
} catch (error) {
  error instanceof HttpError;     // true when the server answered 404
  error.status;                   // 404
  error.data;                     // the parsed error body, e.g. { message: "Not found" }
  error instanceof NetworkError;  // true instead when there was no answer at all
}

Environment

  • Plain JavaScript in a browser page; the tests call the globals createClient, ApiError, HttpError and NetworkError from client.js.
  • The page has no network. The tests replace window.fetch with a fake that records each call and answers with a Response, so call the global fetch when the request is made (do not keep a reference to it from when the file loaded).
  • Timeouts, retries, cancellation, FormData and Blob bodies are out of scope.

Hints

  1. Which steps happen in which order: building the config, the request interceptors, serializing the body, fetch, reading the body, checking the status, the response interceptors?
  2. A class that extends another must call super(…) before touching this. What does each error class add on top of its parent?
  3. How can a remove function find "its" interceptor if the same function was added twice?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…