I have a unique situation that requires some help. Our team is in the process of integrating nestjs into our current express codebase. Previously, we were using Typeorm 0.2 and recently upgraded to 0.3. Due to the fact that we utilize functions instead of classes, making use of datasource dependency injection without extensive refactoring is not feasible for us. Our objective is to access the datasource without relying on nestjs dependency injection.
Previously, we constructed transactions in the following manner:
import { getManager } from 'typeorm';
return getManager().transaction((manager) => {
// perform actions
});
With the upgrade to TypeOrm 0.3, the usage of getManager
has been deprecated. The code compiles successfully and all requests not involving the getManager
function operate as intended. However, when the function containing getManager
is executed, the following error occurs:
ConnectionNotFoundError: Connection "default" was not found.
I attempted to work directly with the datasource, but the dreaded "metadata not found" error surfaces and the code fails to compile at all.
import { getManager } from 'typeorm';
return AppDataSource.transaction((manager) => {
// perform actions
});
Entity metadata for BuyerIndustry#companies was not found. Check if you specified a correct entity object and if it's connected in the connection options.
This is how we configured the datasource and imported it in the AppModule
:
import { ConfigService } from '@nestjs/config';
import { DataSource } from 'typeorm';
import { repositories } from './repositories';
const configService = new ConfigService();
export const AppDataSource = new DataSource({
type: 'postgres',
host: configService.get('POSTGRES_HOST'),
port: configService.get('POSTGRES_PORT'),
username: configService.get('POSTGRES_USER'),
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_DB'),
migrations: [__dirname + '/src/database/migrations/*{.ts,.js}'],
entities: repositories,
synchronize: false,
});
// repositories.ts
export const repositories = [
BuyerIndustry,
Company,
// and all other entities in the application
];
// typeorm.module.ts
import { Global, Module } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { AppDataSource } from './datasource';
@Global()
@Module({
imports: [],
providers: [
{
provide: DataSource,
useFactory: async () => {
await AppDataSource.initialize();
return AppDataSource;
},
},
],
exports: [DataSource],
})
export class CustomTypeOrmModule {}
// main.module.ts
@Module({
imports: [
CustomTypeOrmModule,
// other modules
]
export class AppModule {
constructor(private dataSource: DataSource) {}
}
I am absolutely sure that I have imported ALL entities in the repositories.ts
. Do you have any suggestions on how we can directly access the DataSource
within functions without the need for a class with the datasource injected? Any assistance would be greatly appreciated, thank you!