@metreeca/http - v0.1.1
    Preparing search index...

    Function headers

    • Creates a middleware injecting default header fields into requests.

      Decorates a Fetch implementation with one adding defaults to every request, alongside the fields supplied by the caller: a field already carried by the request is left as it is, so that injected fields stand as defaults an exchange may override on its own terms.

      Important

      Fields supplied by the caller take precedence: a field named by defaults is attached only if the request carries none under that name, whatever its value, and is otherwise dropped. The injected value is never appended to the one in place, and no field is ever removed.

      const client = createFetch(headers({ "Accept": "application/json" }));

      await client("https://api.example.com/data"); // Accept: application/json

      await client("https://api.example.com/data", { // Accept: text/csv, as supplied by the caller
      headers: { "Accept": "text/csv" }
      });

      To impose a field on every exchange, regardless of what the caller supplies, layer a middleware setting it outright, as basic and bearer do for the Authorization field.

      Requests are normalised as Request objects before the fields are attached, preserving the headers and the options carried by a Request input alongside the overrides supplied through init.

      Fields supplied as a HeadersInit value are validated and normalised once when the middleware is created, leaving nothing to compute on the request path; fields repeated under the same name are merged into a comma-separated value, as the Headers constructor prescribes. Fields supplied as a function are resolved and normalised on every request, against the request as it is about to be sent, so that values depending on the exchange, such as a correlation id or a target-specific trait, are computed as it requires. A supplier reporting malformed fields, or failing altogether, rejects the exchange without sending it.

      Field names are matched case-insensitively, as HTTP prescribes, so content-type and Content-Type name the same field both when the request is tested and when the default is attached.

      Parameters

      • defaults: HeadersInit | ((request: Request) => Awaitable<HeadersInit>)

        The default header fields to be injected, or a function computing them for every request

      Returns Middleware

      A Middleware wrapping a Fetch implementation with one injecting the fields of defaults the request doesn't already carry

      If defaults is a HeadersInit value carrying a malformed field name or value