Owen Conti

Fixing Duplicate ID Errors with typeorm-factory

Posted on under TypeScript by Owen Conti.

When creating a factory with typeorm-factory, you have to make sure any dynamic data is handled within a closure, otherwise it'll only run once when the factory is imported.

1const PerkCategoryFactory = new Factory(PerkCategory)
2 .attr('name', faker.lorem.word());

If you define a factory like the above, the faker.lorem.word() will only run once, when the factory is imported. This means if you were expecting a random word for each instance the factory creates, you won't get it. Instead, each factory will have the exact same word.

To fix this, you must use a sequence instead of attr:

1const PerkCategoryFactory = new Factory(PerkCategory)
2 .sequence('name', () => faker.lorem.word());

The sequence will accept a closure as the second argument, which will be invoked whenever the factory creates a new instance.


Thanks for reading this article!

Hopefully you found this article useful! If you did, share it on Twitter!

Found an issue with the article? Submit your edits against the repository.