Skip to content

Commit

Permalink
feat: add verbose retry log attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilmysliwiec committed Jul 5, 2024
1 parent 8f3fd93 commit 0222704
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
11 changes: 11 additions & 0 deletions lib/common/mongoose.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export function getConnectionToken(name?: string) {
export function handleRetry(
retryAttempts = 9,
retryDelay = 3000,
verboseRetryLog = false,
): <T>(source: Observable<T>) => Observable<T> {
const logger = new Logger('MongooseModule');
return <T>(source: Observable<T>) =>
Expand All @@ -32,6 +33,16 @@ export function handleRetry(
})...`,
'',
);
const verboseMessage = verboseRetryLog
? ` Message: ${error.message}.`
: '';

logger.error(
`Unable to connect to the database.${verboseMessage} Retrying (${
errorCount + 1
})...`,
error.stack,
);
if (errorCount + 1 >= retryAttempts) {
throw error;
}
Expand Down
6 changes: 5 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, Connection } from 'mongoose';
import { ConnectOptions, Connection, MongooseError } from 'mongoose';

export interface MongooseModuleOptions extends ConnectOptions {
uri?: string;
Expand All @@ -10,6 +10,10 @@ export interface MongooseModuleOptions extends ConnectOptions {
connectionErrorFactory?: (error: MongooseError) => MongooseError;
lazyConnection?: boolean;
onConnectionCreate?: (connection: Connection) => void;
/**
* If `true`, will show verbose error messages on each connection retry.
*/
verboseRetryLog?: boolean;
}

export interface MongooseOptionsFactory {
Expand Down
8 changes: 6 additions & 2 deletions lib/mongoose-core.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export class MongooseCoreModule implements OnApplicationShutdown {
mongooseConnectionName,
),
).pipe(
handleRetry(retryAttempts, retryDelay),
handleRetry(retryAttempts, retryDelay, options.verboseRetryLog),
catchError((error) => {
throw mongooseConnectionError(error);
}),
Expand Down Expand Up @@ -128,7 +128,11 @@ export class MongooseCoreModule implements OnApplicationShutdown {
mongooseConnectionName,
),
).pipe(
handleRetry(retryAttempts, retryDelay),
handleRetry(
retryAttempts,
retryDelay,
mongooseOptions.verboseRetryLog,
),
catchError((error) => {
throw mongooseConnectionError(error);
}),
Expand Down

0 comments on commit 0222704

Please sign in to comment.