Home > Mobile >  objects lifecycle in Nestjs between classes
objects lifecycle in Nestjs between classes

Time:05-29

I am trying to understand how Nestjs handles persistence of objects. I Nodejs you can declare an object and it will persists for the life of the application. Nestjs however is comprised of as a collaboration of "Classes" similar to Angular. Whereas Angular has BehaviourSubject that can persist an object for the life of the Application I am not sure how to do this in Nestjs wihtout using Redis or some other in-memory-store. For example if I have a controllerA the calls a serviceA (this service has an Object with a value:

  Aobject=[]=[];
  Aobject.push({"test"})).

If I have another controllerB that use DI to access serviceA what is the value of Aobject? can someone explain how Nestjs handles the lifecycle of Aobject between the classes? and do I have use in-memory-store to acheive this?

EDIT: based on the first answer I am editing the question. I am using the default scope since I want all comers to modify Aobject via serviceA. What appears to be happening is that when serviceA is called by controllerB the Aobject is null ...an empty array like it was at initialization. Which is quite puzzling since I expected it to have the last value set by serviceA no matter who initiated the call.

This scenario works the way I am expecting:

cronService calls serviceC....serviceC calls serviceA to set Aobject to ['TEST'] then returns to serviceC...then returns to cronService...cronService then calls serviceA and check the value of Aobject...the value is 'TEST' as expected....but when serviceB calls serviceA the value of Aobject is empty[]. Is it that the scope is controlled by cronService and when we change to serviceB its a new scope.. new instance of Aobject??

CodePudding user response:

It depends what injection scope is used by serviceA. If you don't specify an injection scope, the DEFAULT scope will be used, which means controllerA and controllerB will share a singleton instance of serviceA. Assuming that serviceA has an object Aobject, both controllers will modify the same object, if the modification actions happen through serviceA.

If serviceA uses REQUEST scope, a different instance of serviceA will be created in case of each user request and they will be garbage collected when the requests are completed.

The third injection scope is TRANSIENT scope. In this case, each controller will have a different instance of serviceA, but this instances are created at startup and are not terminated after each request.

  • Related