My application is built with NestJS and TypeORM and I now need to specify relations between entities.
The official documentation shows that I should wrap a single entity inside a module:
The Photo entity belongs to the photo directory. This directory represents the PhotoModule. It's your decision where you gonna keep your model files. From our point of view, the best way's to hold them nearly their domain, in the corresponding module directory.
but how to handle different entities that are releated between each other (e.g. one-to-many, many-to-many, etc...)? Should they live within the same module? How?
I'm facing a similar design decision right now. I have to decide where a table that represents a many-to-many relationship should reside. I'll leave my approach here just in case it works for someone else.
I believe the official documentation you mention has been slightly updated now, they use Users instead of Photos.
The User model file sits in the users directory. This directory contains all files related to the UsersModule. You can decide where to keep your model files, however, we recommend creating them near their domain, in the corresponding module directory.
I decided to put the subyacent concept inside the parent directory. So, if we have the concepts Organization
, Employee
, and an entity representing their many-to-many relationship, let's say, called OrganizationEmployees
.
So, the folder structure would end up looking something like this:
src
│ ...
│
└───organizations
│ │ organizations.dto.ts
│ │ organizations.entity.ts
│ │ organizations.controller.ts
│ │ ...
│ │
│ └───organizationUsers
│ │ organizationUsers.dto.ts
│ │ organizationUsers.entity.ts
│
└───users
│ │ users.dto.ts
│ │ users.entity.ts
│ │ users.controller.ts
│ │ ...
The reasons for such decision are these:
If we focus on the bold part of the documentation quote ("near their domain"), I'd say it's valid to think about these concepts closely related to one of the participants of the many-to-many relationship.
It makes sense from a design point of view. I believe it wouldn't make sense to create a whole module for a concept representing a many-to-many relationship, IF that's pretty much what it's going to represent (no controllers, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With