1

I have two problems using nestJs DI (and unfortunately the documentations are all the same and contains only basic usage information about the topics):

  • what if I construct an AppModule, and simple I need to create a service just in case (currently my rabbitMq handler - served in moleculer - needs a document service instance)
  • what if the document service instance (for rabbitMq) depends on a user instance, which is a dependency for the document service, and in this case the user must be created (injected) in a different way than as usual (when it is used for serving a web request)?
@Injectable()
class DocumentService {
    @Inject('USER') user: IUser;
    @Inject() protected userRepository: UserRepository;
    @Inject() protected documentRepository: DocumentRepository;

    public void saveDocument() {
        ...
    } 
}

where

@Module({
    controllers: [DocumentController]
    providers: [
        // repositories
        UserRepository, DocumentRepository, 
        // services
        DocumentService,
        // user
            {
                provide: 'USER',
                scope: Scope.REQUEST,
                useFactory: (req:Request) => req["user"] ?? null,
            },
        ],
    exports: ['USER'],
})


export class AppModule {}

What I should use is a code like this:

let rabbitMqUser = new user('rabbitMqServiceUser');
// change the IUser not come from request but use this instance for now:
// but use the DI injections describe above for the 'default' web request case
let documentService = pleaseNestJsConstructForMe<DocumentService>(where 'USER'=rabbitMqUser);
Zoltan Hernyak
  • 989
  • 1
  • 14
  • 35
  • 1
    Where is your rabbitMq logic located, is it not a part of NestJS module? – fujy Jul 21 '23 at 15:20
  • No, its not. It is handled by moleculer, separate port, separate everything. All is shared the services between the nestJS web service and the rabbitMq service handler. – Zoltan Hernyak Jul 21 '23 at 18:16
  • If you want to have NestJS instantiate and inject an object for you as per your request `pleaseNestJsConstructForMe`, then it must be registered in a NestJS module list of providers. – fujy Jul 21 '23 at 22:29

0 Answers0