Immutable fetch client builder with query, headers, and JSON
A dashboard team keeps writing the same fetch boilerplate: join URLs, encode query strings, add auth headers, check response.ok. You are asked to build a tiny client that removes it. Because engineers share partially built requests (for example “the orders endpoint with the team header”), every builder must be immutable: adding a query parameter to a shared builder must never leak into other requests.
Implement createApiClient(baseUrl, options).
const api = createApiClient(baseUrl, { headers }?);
api.get(path) // => RequestBuilder (method 'GET')
api.post(path) // 'POST'
api.put(path) // 'PUT'
api.patch(path) // 'PATCH'
api.delete(path) // 'DELETE'
builder.query(params) // => new RequestBuilder with extra query params
builder.header(name, value) // => new RequestBuilder with one header set
builder.json(body) // => new RequestBuilder with a JSON body
builder.send() // => Promise of the parsed response
query, header and json return a new builder. The builder they were called on must behave exactly as before.baseUrl and path with exactly one /, whether or not either side already has one.query() calls merge. A key set again keeps its original position and takes the new value.null or undefined.{ tag: ['a', 'b'] } becomes tag=a&tag=b.String(value) and encoded the way URLSearchParams does it (a space becomes +).? only when at least one parameter remains.options.headers, then apply header() calls in order; a later value for the same name wins.json(body) sets the body to JSON.stringify(body) and the header content-type to application/json.fetch(url, init) exactly once with:
init.method: the uppercase method.init.headers: a plain object of lowercase names to string values.init.body: the JSON string, or no body property at all when json() was never called.response.ok is false, reject with an Error whose status property is response.status and whose message contains the status number.204, resolve with null without reading the body.await response.json().fetch reject unchanged.send() makes a new request.const api = createApiClient('https://api.shop.dev/v2/', {
headers: { Authorization: 'Bearer t0k3n' },
});
const orders = api.get('/orders').header('X-Team', 'payments');
await orders.query({ status: 'open', page: 1 }).send();
// fetch('https://api.shop.dev/v2/orders?status=open&page=1', {
// method: 'GET',
// headers: { authorization: 'Bearer t0k3n', 'x-team': 'payments' },
// })
await orders.query({ tag: ['gift', 'rush'], note: undefined }).send();
// fetch('https://api.shop.dev/v2/orders?tag=gift&tag=rush', ...)
// `orders` itself still has no query parameters.
await api.post('refunds').json({ orderId: 'o_17', amount: 12.5 }).send();
// fetch('https://api.shop.dev/v2/refunds', {
// method: 'POST',
// headers: { authorization: 'Bearer t0k3n', 'content-type': 'application/json' },
// body: '{"orderId":"o_17","amount":12.5}',
// })
await api.get('/missing').send();
// rejects: Error('Request failed with status 404'), error.status === 404