Transforming Requests and Responses Together

Avatar of Hemanta SundarayHemanta Sundaray

Sometimes you need to coordinate between the request and the response. For example, you might want to start a timer when the request is built and log the elapsed time when the response arrives. HttpClient.transform() gives you access to both.

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect } from "effect";
function fetchFromApi() {
return Effect.gen(function* () {
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.transform((responseEffect, request) =>
Effect.gen(function* () {
const start = Date.now();
console.log(`--> ${request.method} ${request.url}`);
const response = yield* responseEffect;
const elapsed = Date.now() - start;
console.log(`<-- ${response.status} (${elapsed}ms)`);
return response;
}),
),
);
const response = yield* client.get("https://dummyjson.com/users/1");
const user = yield* response.json;
return user;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(fetchFromApi()).then((user) => {
console.log("User:", user.firstName, user.lastName);
});

Output:

Terminal
--> GET https://dummyjson.com/users/1
<-- 200 (643ms)
User: Emily Johnson

The function passed to transform receives two arguments: the response effect and the request that triggered it. You yield* the response effect to actually execute the request, and you can do work before and after.

You must explicitly yield the response effect, or the request won’t be sent at all.

Use transform when you need to correlate requests with their responses, like timing, tracing, or conditional retries based on request properties.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.