Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I place related entities together in the same module?

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?

like image 699
Francesco Borzi Avatar asked Nov 17 '18 19:11

Francesco Borzi


1 Answers

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:

  1. 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.

  2. 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).

like image 70
aleclara95 Avatar answered Nov 09 '22 08:11

aleclara95