Skip to content
Logo

Composition

You can make one schema from another, keep only some of a schema's fields, or override a single call on a Fabricator you already built. All of these work together.

.extend() — add or replace fields

const IdentifiableProductSchema = ProductSchema.extend(({ base }) => ({
  id: T.number.integer.sequence,
}));

This combines the base schema's fields with the ones you return. A new field is added. A field with the same name as an existing one replaces it entirely, even if both are objects; their fields are not merged. base is the original set of fields, in case the new ones need to refer to it. Ignore it if you don't need it.

.refine() — add fields computed from fabricated data

const WithSlug = ProductSchema.refine(({ compute }) => ({
  slug: compute(T.string)
    .from(["name"])
    .as(({ fabricated }) => fabricated.name.toLowerCase().replace(/\s+/g, "-")),
}));

This works like .extend(), but the new fields are computed from the base schema's fabricated values. See Objects for how compute works. Refine stages chain, so a later .refine() can read a field an earlier one computed.

.override() — bake fixed values into a schema

const WidgetSchema = ProductSchema.override({
  name: "Widget",
  pricing: { currency: "USD" },
});
 
const widget = new Fabricator(WidgetSchema).fabricate();

This returns a new schema and involves no randomness. The named fields always produce the fixed value. Every other field keeps the same random stream it would have without the override (see Reproducibility). In a nested object like pricing, only the fields you name are fixed. Overrides chain: in .override(a).override(b), b wins where they conflict.

T.pick and T.omit — keep some fields

const Summary = T.pick(ProductSchema, ["id", "name"]);
const WithoutPricing = T.omit(ProductSchema, ["pricing"]);

Both return a new object schema with fewer fields. If a computed field you kept reads a field you dropped, the dropped field is still fabricated for it but doesn't appear in the result. See T.pick.

.fabricate(overrides) — a per-call override, not a new schema

const Product = new Fabricator(ProductSchema);
const widget = Product.fabricate({ name: "Widget" });

This is the lightweight version of .override(). Instead of making a new schema, it overrides one call on a Fabricator you already built, and every other field is fabricated as usual. See Objects for Omitted and how nested objects are handled.

Extending a subtype

const ElectronicsSchema = ProductSchema.extend(() => ({
  category: T.always("electronics"),
}));
 
const laptop = new Fabricator(ElectronicsSchema).fabricate({ name: "Laptop" });

.extend(), .refine(), .override(), T.pick, and T.omit all return ordinary schemas, so you can combine them with each other and with .fabricate(overrides). Here, a fixed field in the schema (T.always("electronics")) and a per-call override ({ name: "Laptop" }) are just two steps in the same chain.