1- import { DynamicModule , Module , Global , Provider } from '@nestjs/common' ;
1+ import {
2+ DynamicModule ,
3+ Module ,
4+ Global ,
5+ Provider ,
6+ OnModuleDestroy ,
7+ Inject ,
8+ Logger ,
9+ } from '@nestjs/common' ;
10+ import { ModuleRef } from '@nestjs/core' ;
211import {
312 ExpressCassandraModuleOptions ,
413 ExpressCassandraModuleAsyncOptions ,
@@ -7,10 +16,18 @@ import {
716import { EXPRESS_CASSANDRA_MODULE_OPTIONS } from './express-cassandra.constant' ;
817import { getConnectionToken , handleRetry } from './utils/cassandra-orm.utils' ;
918import { createClient } from 'express-cassandra' ;
19+ import { defer } from 'rxjs' ;
20+ import { map } from 'rxjs/operators' ;
1021
1122@Global ( )
1223@Module ( { } )
13- export class ExpressCassandraCoreModule {
24+ export class ExpressCassandraCoreModule implements OnModuleDestroy {
25+ constructor (
26+ @Inject ( EXPRESS_CASSANDRA_MODULE_OPTIONS )
27+ private readonly options : ExpressCassandraModuleOptions ,
28+ private readonly moduleRef : ModuleRef ,
29+ ) { }
30+
1431 static forRoot ( options : ExpressCassandraModuleOptions = { } ) : DynamicModule {
1532 const expressModuleOptions = {
1633 provide : EXPRESS_CASSANDRA_MODULE_OPTIONS ,
@@ -45,6 +62,15 @@ export class ExpressCassandraCoreModule {
4562 } ;
4663 }
4764
65+ async onModuleDestroy ( ) {
66+ if ( this . options . keepConnectionAlive ) {
67+ return ;
68+ }
69+ Logger . log ( 'Closing connection' , 'ExpressCassandraModule' ) ;
70+ const connection = this . moduleRef . get ( getConnectionToken ( this . options ) ) ;
71+ connection && ( await connection . closeAsync ( ) ) ;
72+ }
73+
4874 private static createAsyncProviders (
4975 options : ExpressCassandraModuleAsyncOptions ,
5076 ) : Provider [ ] {
@@ -81,7 +107,13 @@ export class ExpressCassandraCoreModule {
81107 private static async createConnectionFactory (
82108 options : ExpressCassandraModuleOptions ,
83109 ) : Promise < any > {
84- const { name, retryAttempts, retryDelay, ...cassandraOptions } = options ;
85- return await createClient ( cassandraOptions ) ;
110+ const { retryAttempts, retryDelay, ...cassandraOptions } = options ;
111+ const client = await createClient ( cassandraOptions ) ;
112+ return await defer ( ( ) => client . initAsync ( ) )
113+ . pipe (
114+ handleRetry ( retryAttempts , retryDelay ) ,
115+ map ( ( ) => client ) ,
116+ )
117+ . toPromise ( ) ;
86118 }
87119}
0 commit comments