darbaidze2020
darbaidze2020

Reputation: 346

NestJS project architecture: how to avoid dependencies between modules

I have several modules in NestJS:

  1. StudentModule
  2. FinanesModule
  3. GroupModule
  4. ScoresModule
  5. SubjectModule

A module includes model, repository, service, controller related to single resource or functionality.

Before crud operations, I need to check if we can update/delete some resource(student, group, etc.). For example, we cannot delete subject, while some students are studying it.

After some operations, I want to call some "side-effect" operations, for example:

How can I organize project architecture, to avoid "wrong" dependencies?

If I call ScoresService.createEmptySheet(...args) method in StudentService.create() method, it would make StudentModule as a dependent of ScoresModule(as ScoresService is a part of ScoresModule) which seems to be wrong, as student module exists independently from finances module, actually, a finances are depended on student, not vice versa.

Do you think, it's normal to make StudentModule dependent on ScoresModule?!

In other words I need to organize communication between modules without make them dependent on each other when logically they aren't.

P.S I can't use SQL's foreign keys, I am using MongoDB.

Upvotes: 2

Views: 1383

Answers (3)

Abdul Wahab
Abdul Wahab

Reputation: 1

if you want that your module does not depend upon each other. then I think you can use Event Emitter package to communicate between the modules. https://docs.nestjs.com/techniques/events

open for suggestions

Upvotes: 0

Gvozden Miskovic
Gvozden Miskovic

Reputation: 415

I would say that this question points at something much broader than NestJs modules in particular and aims at Software Architecture as a whole.

To answer your question specifically your intuition is likely correct, making UserService depend upon ScoresService is not the best solution in a larger system.

Depending on the specific different solutions would be correct but it may be as simple as creating a third service UserScoreService which depends upon both ScoresService and UserService allowing them to remain independent of each other.

Speaking more broadly, if you are interested in knowing more about this topic I recommend checking out Robert C. Martin's Clean Architecture and Hexagonal Architecture.

Upvotes: 4

coda
coda

Reputation: 111

You could look into Pub-Sub pattern, if you want that kind of decoupling (i.e. https://github.com/glebbash/nestjs-pubsub-core).

Upvotes: 1

Related Questions