Custom types
registry is the set of builders you get as T from initialize(). It is exported so you can extend it before calling initialize:
import { initialize, registry } from "@ghostry/fabricator";
const types = registry.extend(({ T }) => ({
category: {
...T.enum.uniform(["electronics", "clothing", "food"]),
electronics: T.always("electronics"),
clothing: T.always("clothing"),
food: T.always("food"),
},
}));
const { T } = initialize({ types });
T.category; // a random category
T.category.electronics; // always "electronics".extend() deep-merges the object you return into the registry, so other builders are left alone. Chain several .extend() calls to add more.
The "namespace with a default" pattern
A custom type can be used on its own (T.category) and also hold named variants (T.category.electronics). To do that, spread an existing Schema and add properties next to it. T.date.past, T.date.future, and T.number.integer.sequence work the same way:
category: {
...T.enum.uniform(['electronics', 'clothing', 'food']),
electronics: T.always('electronics'),
clothing: T.always('clothing'),
food: T.always('food'),
}Bringing a dynamic data library
For faker, use the faker extension instead of wiring it up yourself. It is a registry.extend callback, so it combines with anything else on this page, and its builders draw from fabricator's randomness:
import { fakerExtension } from "@ghostry/fabricator-extension-faker-v10";
const types = registry
.extend(fakerExtension({ locale: ["base", "en"] }))
.extend(({ T }) => ({
category: T.enum.uniform(["electronics", "clothing", "food"]),
}));
const { T } = initialize({ types });
T.faker.person.fullName();
T.category;For any other library, or for one-off logic, write your own producer:
const types = registry.extend(({ T }) => ({
person: {
fullName: T.string.as(() => faker.person.fullName()),
email: T.string.as(() => faker.internet.email()),
},
}));T.string.as(produce) replaces how a string is generated with your own function. produce receives { random, clock }, the same as T.opaque's producer, but it doesn't have to use them. A call like faker.person.fullName() above uses faker's own randomness, so that field is not reproducible. To keep it reproducible, draw from random in the producer. See T.opaque for producers built around random.
