Provide the client
Give a program the HttpClient that the client's layer needs, then run it.
Api.layer builds your client, but it doesn't bring the HttpClient that
sends the requests. You provide one where you run your program, and that
separation is what lets a test swap in a fake one. This page shows how to
provide it, how to set fetch options such as cookies, and how to build the
HttpClient into the layer when you'd rather not provide it.
Provide an HttpClient where you run the program
Provide FetchHttpClient.layer, Effect's HttpClient built on fetch, to
Api.layer, then provide the result to your program and run it:
import * as from "effect/Effect";
import * as from "effect/http/FetchHttpClient";
import * as from "effect/Layer";
import { } from "@monarcode/effetch";
export class extends .<>()("Api", {
: "https://api.example.com",
}) {}
export const = ..(.(.));
export const = .(function* () {
const = yield* ;
return yield* .("/health");
});
await .(.(.()));ApiLive usually sits next to the other layers of your app. Provide it
one time, where the program runs: each Effect.provide builds the client
again, so providing it inside each function that calls the API builds a
separate client for every one of them.
Effect's HttpClient adds tracing headers (traceparent and b3) to
every request. In a browser, a call to a cross-origin API that doesn't
allow them fails the CORS preflight. See Platform notes to turn
them off.
Set fetch options for every request
FetchHttpClient.RequestInit sets the fetch options every request starts
from, such as credentials, cache or redirect. Provide it next to
FetchHttpClient.layer, and every call the client makes uses it, since the
client keeps the services it was built with. Each request's method, headers
and body still come from the call.
The most common use is a browser app that calls an API on another origin and needs its cookies sent. Send cookies shows that setup, with what the API's CORS response has to allow.
Build the HttpClient into the layer
If you'd rather have Api.layer provide the HttpClient too, override the
layer in the class:
import * as from "effect/http/FetchHttpClient";
import * as from "effect/Layer";
import { } from "@monarcode/effetch";
export class extends .<>()("Api", {
: "https://api.example.com",
}) {
static override readonly = super..(
.(.),
);
}The override can need less than the original layer, but not more, and it
can't add an error. To add requirements, build a separate layer from
Api.layer instead.
What's next
- Make a call: call the API with the client's methods.
- Test with a fake backend: provide a fake
HttpClientinstead of the real one. - Derive a client: make a second client from the first one's config.