Hello everyone, I have a small and fast question about forRootAsync method. I am using forRootAsync as a dynamic database connection builded from string which another service gives to me (with useClass parameter). Until this point everything is cool and okay, I just wonder to know if the connection this module generates is unique. I mean, if somebody else want to consume my API and gives the same url to the DB does this generate another DB connection or it reuse the existing one. If it reuse connection is there a method to singe use connection?
#question about forRootAsync connection
33 messages · Page 1 of 1 (latest)
How is the connection generated? I don't really follow the question here. The connection (unless request scoped) gets created at server startup, and should pretty much be there until server shutdown, yeah?
In my case I am using forRootAsync in the app module so there is no connection until API call
Why is there no connection until API calls?
TypeOrmModule.forRootAsync({
useClass: TypeOrmConfigService,
});
Okay? What is TypeOrmConfigService?
@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
createTypeOrmOptions(): TypeOrmModuleOptions {
return {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'test',
entities: [],
synchronize: true,
};
}
}
Yeah, that'll create the connection when you start the server
its an example from the docs but its fine for me
its not actually
But it does
If it was I would have an error since I have no connection at the beggining
to generate return object I actually ask another service for a string to the database
Okay, step back for a moment: is this @nestjs/typeorm or your own module implementation?
@Injectable()
export class TypeOrmConfigService implements TypeOrmOptionsFactory {
async createTypeOrmOptions(): Promise<TypeOrmModuleOptions> {
await askForString = askForStringMethod()
return parse(askForString )
}
}
yes
Okay, nest's Typeorm module connects to the database as soon as it is able to do it can create the repositories that are necessary for the services that are needed for the controllers. That's how nest works
okay so what is the difference between forRoot and forRootAsync
With forRootAsync you're able to get the values for the configuration from other providers, like a ConfigService or an asynchronous call to a secret store, rather than relying on magic strings or values from process.env that may not have yet been set
Yes. Just like it is with forRoot
So here is my question, do I have "native" way to generate 1 connection per API call / user o I need to inject that connection in my service class and close it manually?
You can make the connection REQUEST scoped as described in the Scope Hierarchy docs
Yep
I already have that
so Injecting request I force the connection be used as a single connection per call
Yes, as I literally said in my first message