Skip to content

Commit

Permalink
feat(mongoose): limit mongoose connection retries for simpler debuggi…
Browse files Browse the repository at this point in the history
…ng (#24)
  • Loading branch information
antoinezanardi committed Mar 15, 2023
1 parent fa51245 commit 74a3d15
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/config/database/database.helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { ConfigService } from "@nestjs/config";
import type { MongooseModuleFactoryOptions } from "@nestjs/mongoose";

function mongooseModuleFactory(configService: ConfigService): MongooseModuleFactoryOptions {
const connectionTimeoutMs = 3000;
const host = configService.getOrThrow<string>("DATABASE_HOST");
const port = configService.getOrThrow<string>("DATABASE_PORT");
const databaseName = configService.getOrThrow<string>("DATABASE_NAME");
Expand All @@ -13,6 +14,9 @@ function mongooseModuleFactory(configService: ConfigService): MongooseModuleFact
authSource: "admin",
user: username,
pass: encodeURIComponent(password),
retryAttempts: 3,
retryDelay: connectionTimeoutMs,
serverSelectionTimeoutMS: connectionTimeoutMs,
};
}

Expand Down
7 changes: 6 additions & 1 deletion tests/unit/specs/config/database/database.helper.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { ConfigService } from "@nestjs/config";
import type { MongooseModuleFactoryOptions } from "@nestjs/mongoose";
import { when } from "jest-when";
import { mongooseModuleFactory } from "../../../../../src/config/database/database.helper";

describe("Database Helper", () => {
const connectionTimeoutMs = 3000;
const configServiceMock: Partial<ConfigService> = { getOrThrow: jest.fn() };
const host = "localhost";
const port = "1234";
Expand All @@ -20,12 +22,15 @@ describe("Database Helper", () => {

describe("mongooseModuleFactory", () => {
it("should return connection string when called.", () => {
expect(mongooseModuleFactory(configServiceMock as ConfigService)).toStrictEqual({
expect(mongooseModuleFactory(configServiceMock as ConfigService)).toStrictEqual<MongooseModuleFactoryOptions>({
uri: `mongodb://${host}:${port}`,
dbName: databaseName,
authSource: "admin",
user: databaseUserName,
pass: encodeURIComponent(databasePassword),
retryAttempts: 3,
retryDelay: connectionTimeoutMs,
serverSelectionTimeoutMS: connectionTimeoutMs,
});
});
});
Expand Down

0 comments on commit 74a3d15

Please sign in to comment.