Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix minor bug: ensure single database connection on server startup #2240

Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion src/config/plugins/loadPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import mongoose from "mongoose";
// Only loads plugin data for the time if it's not currently present in the database
const loadPlugins = async (): Promise<void> => {
try {
await mongoose.connect(process.env.MONGO_URI as string);
await mongoose.connect(process.env.MONGO_DB_URL as string);
logger.info("\x1b[1m\x1b[32m%s\x1b[0m", `Connected to the database`);
const res = await Plugin.find();
const databaseTitle = mongoose.connection.db.databaseName;
Expand Down
11 changes: 11 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ import { MONGO_DB_URL } from "./constants";
import { logger } from "./libraries";
import { checkReplicaSet } from "./utilities/checkReplicaSet";

lokeshwar777 marked this conversation as resolved.
Show resolved Hide resolved
let isConnected = false;
let session!: mongoose.ClientSession;

export const connect = async (dbName?: string): Promise<void> => {
if (isConnected) {
return;
}

try {
await mongoose.connect(MONGO_DB_URL as string, {
dbName,
Expand All @@ -17,6 +22,7 @@ export const connect = async (dbName?: string): Promise<void> => {
} else {
logger.info("Session not started --> Not Connected to a replica set!");
}
isConnected = true;
} catch (error: unknown) {
if (error instanceof Error) {
const errorMessage = error.toString();
Expand Down Expand Up @@ -52,8 +58,13 @@ export const connect = async (dbName?: string): Promise<void> => {
};

export const disconnect = async (): Promise<void> => {
if (!isConnected) {
logger.warn("No active database connection to disconnect.");
return;
}
session?.endSession();
await mongoose.connection.close();
isConnected = false;
};

export { session };