I have a project still way back on https://github.com/w3tecch/typeorm-seeding , and I'd like to move factories to typeorm-factory.
So I'm migrating away from using context (which was removed in your other library). Using the class-based extends
factories (nice API design, btw!), I was thinking of using constructors to replace context, like this:
type FooFactoryContext = { n: number };
export class FooFactory extends Factory<Foo> {
constructor(private ctx?: FooFactoryContext) {
super();
}
protected entity = Foo;
protected dataSource = dataSource;
protected attrs(): FactorizedAttrs<Foo> {
return {
description: `item number ${this.ctx?.n || faker.datatype.number(10)}`,
user: new SingleSubfactory(UserFactory),
};
}
}
new FooFactory().make({ description: "stuff" });
new FooFactory({ n: 5 }).make();
Is something like this what you had in mind as a replacement for context?
I hit a wall with a pattern in our old usage that I'm struggling to replace. We're passing information from one factory's context into a subfactory's context, like this:
define<Foo, FooFactoryContext>(Foo, (_, context) => {
const foo = new Foo();
foo.title = faker.random.words(3);
foo.bar = BarFactory({stuff: context?.stuff}) as any;
If I continue down the path of using constructors, I think what I need is, a way to pass in a constructed factory into a subfactory, instead of passing in a constructible. Something like this:
protected attrs: FactorizedAttrs<User> = {
country: new SingleSubfactory(new CountryFactory({customStuff:"here"})),
}
Or maybe, alternatively, instead of using constructors, I could pass in some "synthetic" attrs
that don't have corresponding properties on the Entity:
protected attrs: FactorizedAttrs<User> = {
country: new SingleSubfactory(CountryFactory, {
name: faker.address.country(),
extraThing: "this doesn't exist on the entity, but could be used by factories"
}),
}
Maybe this is what is meant by "Attributes objects are superset from the original entity attributes." ? (ref) Does this happen to already work? (TypeScript errors discouraged me, but I haven't tried it interactively)
Do either of these options seem viable? Is there another way to achieve what I'm after?
Thanks for the libraries!