Validating Request Bodies

Avatar of Hemanta SundarayHemanta Sundaray

If you want to validate your request body with a Schema before sending it, you can use HttpClientRequest.schemaBodyJson().

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>, 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.

Sign in to save progress

Stay in the loop

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