Skip to content

Commit 49a1732

Browse files
Merge pull request #1958 from IRCraziestTaxi/feat-typeorm-connection-factory
docs(@nestjs/typeorm): add documentation for connectionFactory feature
2 parents eb0be3f + 49791c3 commit 49a1732

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

content/techniques/sql.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,6 +754,39 @@ This construction works the same as `useClass` with one critical difference - `T
754754

755755
> info **Hint** Make sure that the `name` property is defined at the same level as the `useFactory`, `useClass`, or `useValue` property. This will allow Nest to properly register the connection under the appropriate injection token.
756756
757+
#### Custom Connection Factory
758+
759+
In conjunction with async configuration using `useFactory`, `useClass`, or `useExisting`, you can optionally specify a `connectionFactory` function which will allow you to provide your own TypeORM connection rather than allowing `TypeOrmModule` to create the connection.
760+
761+
`connectionFactory` receives the TypeORM `ConnectionOptions` configured during async configuration using `useFactory`, `useClass`, or `useExisting` and returns a `Promise` that resolves a TypeORM `Connection`.
762+
763+
```typescript
764+
TypeOrmModule.forRootAsync({
765+
imports: [ConfigModule],
766+
inject: [ConfigService],
767+
// Use useFactory, useClass, or useExisting
768+
// to configure the ConnectionOptions.
769+
useFactory: (configService: ConfigService) => ({
770+
type: 'mysql',
771+
host: configService.get('HOST'),
772+
port: +configService.get<number>('PORT'),
773+
username: configService.get('USERNAME'),
774+
password: configService.get('PASSWORD'),
775+
database: configService.get('DATABASE'),
776+
entities: [__dirname + '/**/*.entity{.ts,.js}'],
777+
synchronize: true,
778+
}),
779+
// connectionFactory receives the configured ConnectionOptions
780+
// and returns a Promise<Connection>.
781+
connectionFactory: async (options) => {
782+
const connection = await createConnection(options);
783+
return connection;
784+
},
785+
});
786+
```
787+
788+
> info **Hint** The `createConnection` function is imported from the `typeorm` package.
789+
757790
#### Example
758791

759792
A working example is available [here](https://github.com/nestjs/nest/tree/master/sample/05-sql-typeorm).

0 commit comments

Comments
 (0)