Effectful Transforms

Avatar of Hemanta SundarayHemanta Sundaray

Sometimes a request transformation needs to perform an effect: reading from a config service, fetching a token, or generating a unique ID.

HttpClient.mapRequestEffect() is the effectful counterpart to mapRequest.

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.mapRequestEffect((request) =>
Effect.gen(function* () {
// Simulate fetching a dynamic request ID
const requestId = yield* Effect.sync(
() => `req-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
);
return request.pipe(
HttpClientRequest.prependUrl("https://dummyjson.com"),
HttpClientRequest.setHeader("X-Request-Id", requestId),
);
}),
),
);
const response = yield* client.get("/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
User: Emily Johnson

The key difference from mapRequest is that the callback returns an Effect<HttpClientRequest, E, R> instead of a plain HttpClientRequest. This means you can yield effects inside the transformation. You can access services, read config, generate values, or even perform preliminary network calls. If the effectful transform fails, that error gets added to the client’s error channel.

Sign in to save progress

Stay in the loop

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