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.
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 itEffect.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:
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:
HttpClientRequest.schemaBodyJson(AddRecipeBody)(recipe);// ^^^^^^^^^^^^ ^^^^^^// schema dataThis returns an Effect<HttpClientRequest, HttpBodyError>, just like bodyJson, so you need yield* to unwrap it.