Skip to main content

HTTP

Introduction

HTTP implementation provides makeHttpAdapter/makeHttpAdapterWith and multiple other features which help using Foscia as an HTTP client. It is also the foundation of JSON:API and REST implementations.

Implementations

makeHttpAdapter

This implementation of the adapter will execute context through HTTP requests using the fetch API.

The adapter returns fetch Response objects as data.

It will build fetch Request objects using the context, and handles multiple use cases such as:

  • Dynamic endpoint based on targeted models, IDs, etc.
  • String or object query parameters using a serializer.
  • Various request body typologies.
  • Requests cancellation through AbortController.
  • Errors handling through custom errors classes.
  • Requests/responses/errors transformation.
  • Defaults to JSON data for request/response bodies with appropriate headers.

Usage

import { makeHttpAdapter, makeHttpAdapterWith, paramsSerializer } from '@foscia/http';

// Using blueprint (preconfigured with sensible defaults).
const { adapter } = makeHttpAdapter({
/* ...configuration */
});
// Using constructor (no default configuration provided).
const adapter = makeHttpAdapterWith({
serializeParams: paramsSerializer,
/* ...configuration */
});

const response = await adapter.execute({
/* ...context */
});

Configuration

NameTypeDescription
fetchfetchfetch implementation to use. Default to globalThis.fetch.
baseURLstring | nullBase URL to merge with path when building the request endpoint. Default to /.
buildURL(urlContext: HttpURLContext, context: {}) => stringCustomize the URL parts joining function.
serializeParams(params: Dictionary) => string | undefinedFunction to serialize a query param object.
defaultHeadersDictionary<string>Default headers to use in the request.
defaultBodyAs((body: unknown, headers: Dictionary<string>) => Awaitable<BodyInit>) | nullDefault body transformation. Default to JSON.stringify(). If set to null, body won't be transformed.
defaultResponseReader(response: Response) => any | undefinedDefault reader for the response's data before passing to deserializer. Default to response.json().
appendParams(context: {}) => Dictionary<any>Define additional request query parameters based on context.
appendHeaders(context: {}) => Dictionary<string>Define additional request headers based on context.
requestTransformers((request: Request) => Awaitable<Request>)[]Functions to transform a request object before sending.
responseTransformers((response: Response) => Awaitable<Response>)[]Functions to transform a response object after a successful request.
errorTransformers((error: unknown) => Awaitable<unknown>)[]Functions to transform an error after a fetch error or an unsuccessful request.

Defined in