The right folder structure for many-to-many relations

Viewed 1600

I follow the most common structure for nestjs where I have separate folder for each domain

src/
  user/
    controllers/
      user.controller.ts
    repositories/
      user.repository.ts
    services/
      user.service.ts
    user.module.ts
  team/
    // the same as above but for team entity
    team.module.ts
  app.module.ts

In my application, I have many-to-many relations between user and team. So, users can have many teams, as teams can have many users. For this purpose, I created table user_teams and an obvious separate repository for this table. In most of places in my application I need to use functions like getAllUsersInTeam(idTeam: number) and getAllTeamsBelongsToUser(idUser: number) and I have implemented this functions in repository UserTeamRepository. My question is where the right place to keep this repository file? In which module? I have several ideas

  1. Create a separate folder on the same level as the main domain entities

    src/
      user/
        // user module files
      team/
        // team module files
      user-team/
        repositories/
          user-team.repository.ts
        user-team.module.ts
    

    In this case, potentially I will have a lot of folders for each many-to-many relations which will bring confusing and messing in the project.

  2. Keep UserTeamRepository in some of the modules user or team.

    src/
      user/
        repositories/
          user-team.repository.ts
      // or
      team/
        repositories/
          user-team.repository.ts
    

    In this case I see problem with understading of the project. Why we keep one relations in one folder, but other we decided to keep in another way. How to fast search these kind of relations. I think new developers will be confused where find needed relations and where to keep new relations, cuz in good arhitecture should be no questions where to keep new class.

I'm open to any discussions and thoughts. Thanks for feedback in advance!

1 Answers

It is strange to me that you decided to have an UserTeamRepository at all.

If you want a method getAllUsersInTeam, it should be in UserRepository since you are requesting Users. If you want a method getAllTeamsBelongsToUser, it should be in TeamRepository since you are requesting Teams.

Then, each of these methods is responsible to join on your middle table to accomplish its mission.

Related