I have a NestJS application utilizing TypeORM for database access.
TypeORM has deprecated how getConnection
and getConnectionManager
can be used. I need direct access to it for dealing with transactions.
How to deal with this nowadays?
The answer at getConnection/getRepository typeorm is deprecated is not helpful and can't be applied on NestJS applications.
My app.module.ts
looks like this:
const connectionOptions: ConnectionOptions = {
type: 'postgres',
host: config.host,
port: config.port,
username: config.user || 'postgres',
// ...
}
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
cache: true,
load: [configuration],
}),
TypeOrmModule.forRoot({
...connectionOptions,
autoLoadEntities: true,
}),
For handling transactions, I found the following docs:
import {getManager} from "typeorm";
await getManager().transaction(async transactionalEntityManager => {
});
Unfortunately, getManager
is deprecated.
In the TypeORM-Gitbook, I found the following examples:
await myDataSource.transaction(async (transactionalEntityManager) => {
// execute queries using transactionalEntityManager
})
However, it is not clear to me how to achieve this global DataSource-instance and how to inject this one into app.module.ts
initialization?
In the answer to the question I mentioned at the beginning, they suggest code like:
export const appDataSource = new DataSource({
// ... options
});
In the scope of a NestJS application, I can't find a suitable place to inject this.
package.json
:
"dependencies": {
"@golevelup/ts-jest": "^0.3.6",
"@nestjs/axios": "^3.0.0",
"@nestjs/common": "^9.0.0",
"@nestjs/config": "^2.3.1",
"@nestjs/core": "^9.0.0",
"@nestjs/jwt": "^10.0.3",
"@nestjs/passport": "^9.0.3",
"@nestjs/platform-express": "^9.0.0",
"@nestjs/swagger": "^6.3.0",
"@nestjs/typeorm": "^9.0.1",
"typeorm": "^0.3.15",
// ...
}
You can keep it like this and simply inject the global DataSource
-Object, that NestJS is using behind the scenes, directly in your Services and Modules:
import { DataSource, Repository } from 'typeorm';
@Injectable()
export class MyFancyService {
constructor(
private dataSource: DataSource
) {}
Read more here: https://docs.nestjs.com/techniques/database