adamdubicki / typeorm-entity-factory

A TypeORM testing utility for bulk inserting entity objects.
MIT License
10 stars 0 forks source link

create different entities #13

Open moltar opened 4 years ago

moltar commented 4 years ago

I'm trying to use this and here's some feedback.

I think there is a design flaw where there is a tight coupling of Entity and EntityFactory.

Here's a use case:

I need to create two types of users: customer and admin.

I defined two factories: CustomerFactory and AdminFactory, both using User entity (just different values).

But when I call init, the name for internal storage is obtained from the Entity class:

https://github.com/adamdubicki/typeorm-entity-factory/blob/a739b3bdec974df33d409064675c553a9e175eb8/src/factory-container.ts#L30

Meaning that if I load two of my above entities, one will override the other, as both of the entities are User.

And I wouldn't be able to create two types of users.

There is a workaround, to create two separate containers, but it doesn't seem to be very ergonomic.

adamdubicki commented 4 years ago

@moltar Good catch - I agree this is a design flaw and should be fixed.

There are a couple of solutions that immediately come to mind.

  1. Implement a state variable. Factory libraries like Laraval allow for an options parameter to be passed in. https://laravel.com/docs/7.x/database-testing#using-factories (see 'states')

Then when creating your entities the syntax could look something like... const books = await bookFactory.saveMany(5, {...options}, 'admin'); Then the factory performs different logic based on the parameter.

  1. Allow for better namespacing of the factory metadata to allow for multiple factories to be used for the same entity.

I am heavily leaning towards (2) as it is more flexible in the longterm. I dislike how Laravel does the options parameters as it encourages 'god factories' which do too much. Option (2) encourages the creation of smaller more specific factories.

moltar commented 4 years ago

I am definitely in favor of (2).