Defining Success Schema

Avatar of Hemanta SundarayHemanta Sundaray

Create a new file at ecom/product/schemas.ts(the ecom folder should be at the root of your project):

ecom/product/schemas.ts
import { Schema } from "effect";
export const productSchema = Schema.Struct({
id: Schema.Number,
title: Schema.String,
description: Schema.String,
price: Schema.Number,
category: Schema.String,
brand: Schema.optionalKey(Schema.String),
});
export const productListSchema = Schema.Struct({
products: Schema.Array(productSchema),
total: Schema.Number,
skip: Schema.Number,
limit: Schema.Number,
});
export type Product = typeof productSchema.Type;
export type ProductList = typeof productListSchema.Type;

When fetching products from the DummyJSON API, we’ll use these schemas to validate that the returned data conforms to the shape we expect.

Note that not all products returned by DummyJSON have a brand field. This is why the brand field is marked as optional. Schema.optionalKey creates an exact optional property, meaning the key can be omitted from the object entirely, but if it’s present, it must match the schema’s type.

Additionally, the DummyJSON API returns 20+ top-level fields for a product, but we have defined only 6 fields in our schema. During validation, Effect Schema strips unknown properties by default. As a result, the extra fields will be silently dropped and our API will only expose the fields we explicitly model.

Sign in to save progress

Stay in the loop

Get notified when Effect RPC related content is published.