If you want to validate your request body with a Schema before sending it, you can use HttpClientRequest.schemaBodyJson().
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>, which is why the request is created with yield* instead of being assigned directly..
Note that the schema validates your data before it’s serialized to JSON. If the data doesn’t match, you get a SchemaError in the error channel. The request is never sent. This catches bugs at the point of construction rather than at the server.