Using schemaBodyJson

Avatar of Hemanta SundarayHemanta Sundaray

HttpClientRequest.schemaBodyJson() adds a validation and transformation step before serialization.

You define an Effect Schema that describes the shape of your request body, and the API ensures your data conforms to it before sending.

http.ts
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
} from "effect/unstable/http";
import { Effect, Schema } from "effect";
const AddRecipeBody = Schema.Struct({
name: Schema.String,
ingredients: Schema.Array(Schema.String),
prepTimeMinutes: Schema.Number,
cookTimeMinutes: Schema.Number,
servings: Schema.Number,
});
function addRecipe(recipe: typeof AddRecipeBody.Type) {
return Effect.gen(function* () {
const client = yield* HttpClient.HttpClient;
const request = yield* HttpClientRequest.post(
"https://dummyjson.com/recipes/add",
).pipe(HttpClientRequest.schemaBodyJson(AddRecipeBody)(recipe));
const response = yield* client.execute(request);
const data = yield* response.json;
return data;
}).pipe(Effect.provide(FetchHttpClient.layer));
}
// Test it
Effect.runPromise(
addRecipe({
name: "Masala Chai",
ingredients: ["black tea", "milk", "ginger", "cardamom", "sugar"],
prepTimeMinutes: 5,
cookTimeMinutes: 10,
servings: 2,
}),
).then((data) => {
console.log("Created recipe:", data);
});

Output:

Terminal
Created recipe: {
id: 51,
name: 'Masala Chai',
ingredients: [ 'black tea', 'milk', 'ginger', 'cardamom', 'sugar' ],
prepTimeMinutes: 5,
cookTimeMinutes: 10,
servings: 2
}

schemaBodyJson is a curried function. You first pass the schema, then the data:

Terminal
HttpClientRequest.schemaBodyJson(AddRecipeBody)(recipe);
// ^^^^^^^^^^^^ ^^^^^^
// schema data

This returns an Effect<HttpClientRequest, HttpBodyError>, just like bodyJson, so you need yield* to unwrap it.

Sign in to save progress

Stay in the loop

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