Skip to content

Commit

Permalink
feat: added onconnectioncreate module option
Browse files Browse the repository at this point in the history
  • Loading branch information
prateekkathal committed Mar 20, 2024
1 parent 399af69 commit 388edd2
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
3 changes: 2 additions & 1 deletion lib/interfaces/mongoose-options.interface.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ModuleMetadata, Type } from '@nestjs/common';
import { ConnectOptions, MongooseError } from 'mongoose';
import { ConnectOptions, MongooseError, Connection } from 'mongoose';

export interface MongooseModuleOptions extends ConnectOptions {
uri?: string;
Expand All @@ -9,6 +9,7 @@ export interface MongooseModuleOptions extends ConnectOptions {
connectionFactory?: (connection: any, name: string) => any;
connectionErrorFactory?: (error: MongooseError) => MongooseError;
lazyConnection?: boolean;
onConnectionCreate?: (connection: Connection) => void;
}

export interface MongooseOptionsFactory {
Expand Down
10 changes: 10 additions & 0 deletions lib/mongoose-core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
connectionFactory,
connectionErrorFactory,
lazyConnection,
onConnectionCreate,
...mongooseOptions
} = options;

Expand All @@ -69,6 +70,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
uri,
mongooseOptions,
lazyConnection,
onConnectionCreate,
),
mongooseConnectionName,
),
Expand Down Expand Up @@ -107,6 +109,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
connectionFactory,
connectionErrorFactory,
lazyConnection,
onConnectionCreate,
...mongooseOptions
} = mongooseModuleOptions;

Expand All @@ -123,6 +126,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
uri as string,
mongooseOptions,
lazyConnection,
onConnectionCreate,
),
mongooseConnectionName,
),
Expand Down Expand Up @@ -191,13 +195,19 @@ export class MongooseCoreModule implements OnApplicationShutdown {
uri: string,
mongooseOptions: ConnectOptions,
lazyConnection?: boolean,
onConnectionCreate?: MongooseModuleOptions['onConnectionCreate'],
): Promise<Connection> {
const connection = mongoose.createConnection(uri, mongooseOptions);

if (lazyConnection) {
return connection;
}

const mongooseOnConnectionCreate = onConnectionCreate || (() => {});
if (mongooseOnConnectionCreate) {
mongooseOnConnectionCreate(connection);
}

return connection.asPromise();
}

Expand Down

0 comments on commit 388edd2

Please sign in to comment.