From 0222704b198100ffd1e04d2310b1b482e4c27592 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20My=C5=9Bliwiec?= Date: Fri, 5 Jul 2024 13:23:27 +0200 Subject: [PATCH] feat: add verbose retry log attribute --- lib/common/mongoose.utils.ts | 11 +++++++++++ lib/interfaces/mongoose-options.interface.ts | 6 +++++- lib/mongoose-core.module.ts | 8 ++++++-- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/common/mongoose.utils.ts b/lib/common/mongoose.utils.ts index 2d42305c..f0e70c55 100644 --- a/lib/common/mongoose.utils.ts +++ b/lib/common/mongoose.utils.ts @@ -19,6 +19,7 @@ export function getConnectionToken(name?: string) { export function handleRetry( retryAttempts = 9, retryDelay = 3000, + verboseRetryLog = false, ): (source: Observable) => Observable { const logger = new Logger('MongooseModule'); return (source: Observable) => @@ -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; } diff --git a/lib/interfaces/mongoose-options.interface.ts b/lib/interfaces/mongoose-options.interface.ts index 7e6176d9..20437201 100644 --- a/lib/interfaces/mongoose-options.interface.ts +++ b/lib/interfaces/mongoose-options.interface.ts @@ -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; @@ -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 { diff --git a/lib/mongoose-core.module.ts b/lib/mongoose-core.module.ts index 4902a53f..0447074a 100644 --- a/lib/mongoose-core.module.ts +++ b/lib/mongoose-core.module.ts @@ -73,7 +73,7 @@ export class MongooseCoreModule implements OnApplicationShutdown { mongooseConnectionName, ), ).pipe( - handleRetry(retryAttempts, retryDelay), + handleRetry(retryAttempts, retryDelay, options.verboseRetryLog), catchError((error) => { throw mongooseConnectionError(error); }), @@ -128,7 +128,11 @@ export class MongooseCoreModule implements OnApplicationShutdown { mongooseConnectionName, ), ).pipe( - handleRetry(retryAttempts, retryDelay), + handleRetry( + retryAttempts, + retryDelay, + mongooseOptions.verboseRetryLog, + ), catchError((error) => { throw mongooseConnectionError(error); }),