Reputation: 71
in my nestjs app I have a service which use a factory service to initialize some kind of adapter. Since all the methods in my service need to use the adapter initialized by the factory service, I was wondering if there is a way to call the factory service just once. I cannot do it in the constructor because it is an asynchronous call.
What's the best way to achieve it?
This is my service:
@Injectable()
export class MyService {
constructor(
private readonly factoryService: FactoryService
) {}
and this is the call that I need to do:
await this.factoryService.createAdapter(adapter);
Upvotes: 3
Views: 4841
Reputation: 80
Looks like if you initialize this service (or a sub service) asynchronously, you'll be able to handle your factory. I was facing a similar situation when I found in the Nest JS documentation asynchronous providers.
https://docs.nestjs.com/fundamentals/async-providers
It felt like an inelegant solution (and too much work to divide the initialization into another sub service...) so at least for the time I used a variable to check the state but at some point later, I'll use the documented approach.
If you choose to use the documentation based example, I found their TypeORM recipe as a nice example of how to set it up properly.
https://docs.nestjs.com/recipes/sql-typeorm
Hope this helps. Please comment any feedback!
Upvotes: 2