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 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
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
10 changes: 10 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import { checkReplicaSet } from "./utilities/checkReplicaSet";
let session!: mongoose.ClientSession;

export const connect = async (dbName?: string): Promise<void> => {
// firstly we check if a connection to the database already exists.
if (mongoose.connection.readyState !== 0) {
// if the connection state is not 0, it means a connection already exists so we return.
return;
}
// if no connection exists, we try to establish a new connection.
try {
await mongoose.connect(MONGO_DB_URL as string, {
dbName,
Expand Down Expand Up @@ -52,6 +58,10 @@ export const connect = async (dbName?: string): Promise<void> => {
};

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