Skip to content
Logo

Batches and relationships

Fabricator has no factory-style assoc. A batch is an array schema, and a foreign key is an enum over ids you already have.

Batches

T.array(schema).whereby({ length: N }) is a batch: one Fabricator for the element, called N times.

const FooSchema = T.object({
  id: T.number.integer.sequence,
  name: T.string.whereby({ length: { min: 1, max: 25 } }),
});
 
const Foos = new Fabricator(T.array(FooSchema).whereby({ length: 10 }));
const foos = Foos.fabricate();
// ids 1 through 10

The array reuses one Fabricator for every element, so a sequence keeps counting across the batch. A second .fabricate() on the same array continues it, giving ids 11 through 20. A new new Fabricator(...) starts again at 1.

const Foo = new Fabricator(FooSchema);
const foos = Array.from({ length: 10 }, () => Foo.fabricate());

This loop gives the same kind of values, but the result is not a schema. It can't be nested in another schema, and coverage/combinatorial have no array to work through.

Referencing a pool

Fabricate the parents first, then extend the child with an enum over their ids.

const BarSchema = T.object({
  id: T.number.integer.sequence,
  title: T.string.whereby({ length: { min: 1, max: 40 } }),
  foo_id: T.number.integer, // stands alone; the pool replaces it below
});
 
const bars = new Fabricator(
  T.array(
    BarSchema.extend(() => ({ foo_id: T.enum.uniform(foos.map((f) => f.id)) })),
  ).whereby({ length: 100 }),
).fabricate();

The pick is part of the schema, so it replays like any other field, and coverage/combinatorial treat each parent id as an option to cover.

Use .weighted when some parents should appear more often than others, and T.nullable(T.enum.uniform(ids)) for an optional foreign key.

Owning versus referencing

A child that creates its own parent nests the parent schema and computes the foreign key from it.

const BarOwningFoo = T.object({
  id: T.number.integer.sequence,
  foo: FooSchema,
}).refine(({ compute }) => ({
  foo_id: compute(T.number.integer)
    .from(["foo"])
    .as(({ fabricated }) => fabricated.foo.id),
}));

For one-to-many, go the other way and nest T.array(BarSchema) on the parent. See Computed fields for .refine(({ compute }) => ...).

Drawing inside a producer

sample and shuffle from @ghostry/fabricator are for picks made inside .as, T.opaque, or a T.derive resolver, where you already have a Stream.

import { shuffle } from "@ghostry/fabricator";
 
T.opaque(({ random }) => shuffle(list, random).slice(0, 2));

Use T.enum instead when the pick can be a schema. coverage/combinatorial can enumerate an enum, but not a pick made inside a producer.