Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(forRoot): Allow connection name as entry param #1030

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .npmignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package-lock.json
tslint.json
tsconfig.json
.prettierrc
ormconfig.json

# github
.github
Expand Down
6 changes: 3 additions & 3 deletions lib/common/typeorm.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export function getCustomRepositoryToken(repository: Function): string {
* @returns {string | Function} The Connection injection token.
*/
export function getConnectionToken(
connection: Connection | ConnectionOptions | string = DEFAULT_CONNECTION_NAME,
connection: { name?: string } | string = DEFAULT_CONNECTION_NAME,
): string | Function | Type<Connection> {
return DEFAULT_CONNECTION_NAME === connection
? Connection
Expand Down Expand Up @@ -107,7 +107,7 @@ export function getConnectionPrefix(
* @returns {string | Function} The EntityManager injection token.
*/
export function getEntityManagerToken(
connection: Connection | ConnectionOptions | string = DEFAULT_CONNECTION_NAME,
connection: { name?: string } | string = DEFAULT_CONNECTION_NAME,
): string | Function {
return DEFAULT_CONNECTION_NAME === connection
? EntityManager
Expand Down Expand Up @@ -157,7 +157,7 @@ export function handleRetry(
);
}

export function getConnectionName(options: ConnectionOptions): string {
export function getConnectionName(options: { name?: string }): string {
return options && options.name ? options.name : DEFAULT_CONNECTION_NAME;
}

Expand Down
27 changes: 13 additions & 14 deletions lib/typeorm-core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {
useValue: options,
};
const connectionProvider = {
provide: getConnectionToken(options as ConnectionOptions) as string,
provide: getConnectionToken(options) as string,
useFactory: async () => await this.createConnectionFactory(options),
};
const entityManagerProvider = this.createEntityManagerProvider(
options as ConnectionOptions,
options,
);
return {
module: TypeOrmCoreModule,
Expand All @@ -68,7 +68,7 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {

static forRootAsync(options: TypeOrmModuleAsyncOptions): DynamicModule {
const connectionProvider = {
provide: getConnectionToken(options as ConnectionOptions) as string,
provide: getConnectionToken(options) as string,
useFactory: async (typeOrmOptions: TypeOrmModuleOptions) => {
if (options.name) {
return await this.createConnectionFactory(
Expand All @@ -87,9 +87,9 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {
inject: [TYPEORM_MODULE_OPTIONS],
};
const entityManagerProvider = {
provide: getEntityManagerToken(options as ConnectionOptions) as string,
provide: getEntityManagerToken(options) as string,
useFactory: (connection: Connection) => connection.manager,
inject: [getConnectionToken(options as ConnectionOptions)],
inject: [getConnectionToken(options)],
};

const asyncProviders = this.createAsyncProviders(options);
Expand All @@ -114,7 +114,7 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {
return;
}
const connection = this.moduleRef.get<Connection>(
getConnectionToken(this.options as ConnectionOptions) as Type<Connection>,
getConnectionToken(this.options) as Type<Connection>,
);
try {
connection && (await connection.close());
Expand Down Expand Up @@ -162,7 +162,7 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {
}

private static createEntityManagerProvider(
options: ConnectionOptions,
options: { name?: string },
): Provider {
return {
provide: getEntityManagerToken(options) as string,
Expand All @@ -173,16 +173,15 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {

private static async createConnectionFactory(
options: TypeOrmModuleOptions,
connectionFactory?: TypeOrmConnectionFactory,
connectionFactory: TypeOrmConnectionFactory = createConnection,
): Promise<Connection> {
const connectionToken = getConnectionName(options as ConnectionOptions);
const createTypeormConnection = connectionFactory ?? createConnection;
const connectionToken = getConnectionName(options);
return await lastValueFrom(
defer(() => {
try {
if (options.keepConnectionAlive) {
const connectionName = getConnectionName(
options as ConnectionOptions,
options,
);
const manager = getConnectionManager();
if (manager.has(connectionName)) {
Expand All @@ -195,10 +194,10 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {
} catch {}

if (!options.type) {
return createTypeormConnection();
return connectionFactory();
}
if (!options.autoLoadEntities) {
return createTypeormConnection(options as ConnectionOptions);
return connectionFactory(options as ConnectionOptions);
}

let entities = options.entities;
Expand All @@ -210,7 +209,7 @@ export class TypeOrmCoreModule implements OnApplicationShutdown {
entities =
EntitiesMetadataStorage.getEntitiesByConnection(connectionToken);
}
return createTypeormConnection({
return connectionFactory({
...options,
entities,
} as ConnectionOptions);
Expand Down
31 changes: 31 additions & 0 deletions ormconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
[
{
"type": "postgres",
"host": "0.0.0.0",
"port": 3306,
"username": "root",
"password": "root",
"database": "test",
"entities": [
"tests/src/**/**.{entity,schema}.{ts,js}"
],
"synchronize": true,
"retryAttempts": 2,
"retryDelay": 1000
},
{
"name": "connection_2",
"type": "postgres",
"host": "0.0.0.0",
"port": 3306,
"username": "root",
"password": "root",
"database": "test",
"entities": [
"tests/src/**/**.entity.{ts,js}"
],
"synchronize": true,
"retryAttempts": 2,
"retryDelay": 1000
}
]
36 changes: 36 additions & 0 deletions tests/e2e/typeorm-multiple-named-databases.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import * as request from 'supertest';
import { Server } from 'http';
import { MultipleNamedDatabasesModule } from '../src/multiple-named-databases.module';

describe('TypeOrm (async configuration)', () => {
let server: Server;
let app: INestApplication;

beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [MultipleNamedDatabasesModule],
}).compile();

app = module.createNestApplication();
server = app.getHttpServer();
await app.init();
});

it(`should return created entity for default connection`, () => {
return request(server)
.post('/photo')
.expect(201, { name: 'Nest', description: 'Is great!', views: 6000 });
});

it(`should return created entity for connection_2`, () => {
return request(server)
.post('/photo/2')
.expect(201, { name: 'Nest', description: 'Is great!', views: 6000 });
});

afterEach(async () => {
await app.close();
});
});
10 changes: 0 additions & 10 deletions tests/ormconfig.json

This file was deleted.

12 changes: 12 additions & 0 deletions tests/src/multiple-named-databases.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '../../lib';
import { PhotoSchemaModule } from './photo/schema/photo-schema.module';

@Module({
imports: [
TypeOrmModule.forRoot({ name: 'default' }),
TypeOrmModule.forRoot({ name: 'connection_2' }),
PhotoSchemaModule,
],
})
export class MultipleNamedDatabasesModule {}
5 changes: 5 additions & 0 deletions tests/src/photo/schema/photo-schema.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,9 @@ export class PhotoSchemaController {
create(): Promise<Photo> {
return this.photoService.create();
}

@Post('2')
create2(): Promise<Photo> {
return this.photoService.create2();
}
}
9 changes: 9 additions & 0 deletions tests/src/photo/schema/photo-schema.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,13 @@ export class PhotoSchemaService {

return await this.photoRepository.create(photoEntity);
}

async create2(): Promise<Photo> {
const photoEntity = new Photo();
photoEntity.name = 'Nest';
photoEntity.description = 'Is great!';
photoEntity.views = 6000;

return await this.photoRepository2.create(photoEntity);
}
}