You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/techniques/sql.md
+33Lines changed: 33 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -754,6 +754,39 @@ This construction works the same as `useClass` with one critical difference - `T
754
754
755
755
> 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.
756
756
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 =awaitcreateConnection(options);
783
+
returnconnection;
784
+
},
785
+
});
786
+
```
787
+
788
+
> info **Hint** The `createConnection` function is imported from the `typeorm` package.
789
+
757
790
#### Example
758
791
759
792
A working example is available [here](https://github.com/nestjs/nest/tree/master/sample/05-sql-typeorm).
0 commit comments