Skip to content
Merged
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
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
20 changes: 13 additions & 7 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 @@ -65,11 +66,10 @@ export class MongooseCoreModule implements OnApplicationShutdown {
await lastValueFrom(
defer(async () =>
mongooseConnectionFactory(
await this.createMongooseConnection(
uri,
mongooseOptions,
await this.createMongooseConnection(uri, mongooseOptions, {
lazyConnection,
),
onConnectionCreate,
}),
mongooseConnectionName,
),
).pipe(
Expand Down Expand Up @@ -107,6 +107,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
connectionFactory,
connectionErrorFactory,
lazyConnection,
onConnectionCreate,
...mongooseOptions
} = mongooseModuleOptions;

Expand All @@ -122,7 +123,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
await this.createMongooseConnection(
uri as string,
mongooseOptions,
lazyConnection,
{ lazyConnection, onConnectionCreate },
),
mongooseConnectionName,
),
Expand Down Expand Up @@ -190,14 +191,19 @@ export class MongooseCoreModule implements OnApplicationShutdown {
private static async createMongooseConnection(
uri: string,
mongooseOptions: ConnectOptions,
lazyConnection?: boolean,
factoryOptions: {
lazyConnection?: boolean;
onConnectionCreate?: MongooseModuleOptions['onConnectionCreate'];
},
): Promise<Connection> {
const connection = mongoose.createConnection(uri, mongooseOptions);

if (lazyConnection) {
if (factoryOptions?.lazyConnection) {
return connection;
}

factoryOptions?.onConnectionCreate?.(connection);

return connection.asPromise();
}

Expand Down