@n7e/http-client
v0.4.1
Published
Configurable HTTP client library.
Downloads
4
Maintainers
Readme
HTTP HttpClient
Configurable HTTP client library.
For further insights, read on.
Installation
To install this library use your favorite package manager. No additional steps are required to start using the library.
npm install @n7e/http-client
This library is implemented in TypeScript but can be used with JavaScript without any additional steps.
HTTP Client
An HTTP client has the ability to send HTTP requests with a very simple API. HTTP clients can be configured (through an HTTP client factory) to process requests/responses using a middleware pipeline.
const response = await client.send(request);
HttpClient
is just an interface describing the functionality of an HTTP client.
To create an HTTP client instance use an
HTTP client factory.
HTTP Client Factory
To create an HTTP client instance you should use a HttpClientFactory
.
import type { HttpClientFactory } from "@n7e/http-client";
function someFunction(clientFactory: HttpClientFactory): void {
const client = clientFactory.createClient();
// ...
}
The createClient()
method takes an optional client name as an argument. This
enables us to configure named clients individually. If no name is provided the
assumed client name is "default".
To configure a named client use the configure()
method. The return value is a
client definition instance which can be used to configure a named client.
clientFactory.configure("name")
.useDefaultRequestTimeout(500)
.addMiddleware(someMiddleware);
Any client created with the "name" name will have the appropriate configuration.
const client = clientFactory.createClient("name");
To configure the default client use the name "default".
clientFactory.configure("default").useDefaultRequestTimeout(500);
HttpClientFactory
is just an interface describing the functionality of an
HTTP client factory. To create a client factory instance you need to reference a
specific implementation.
Default Implementation
This library provides a client factory implementation. It produces clients that use the Fetch API internally to send HTTP requests.
The implementation depends on a ResponseFactory
and a StreamFactory
. Since
the @n7e/http library provides default implementations of those factories here's
an example of how to create a client factory:
import { DefaultHttpClientFactory } from "@n7e/http-client";
import { DefaultResponseFactory, DefaultStreamFactory } from "@n7e/http";
const streamFactory = new DefaultStreamFactory();
const responseFactory = new DefaultResponseFactory(streamFactory);
const clientFactory = new DefaultHttpClientFactory(responseFactory, streamFactory);
This implementation allows you to provide a custom fetch method implementation that will be used instead of the global method. This is very useful for test scenarios.
clientFactory.useFetchImplementation(customFetchImplementation);