Skip to content

Commit

Permalink
backend refactor db setup
Browse files Browse the repository at this point in the history
  • Loading branch information
Darkzarich committed Jan 1, 2025
1 parent 3b0c24f commit 306e9fd
Show file tree
Hide file tree
Showing 5 changed files with 79 additions and 72 deletions.
2 changes: 1 addition & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"express-session": "^1.18.1",
"helmet": "^7.1.0",
"lodash-es": "^4.17.21",
"mongoose": "^5.7.5",
"mongoose": "^5.13.23",
"mongoose-autopopulate": "^0.9.1",
"morgan": "^1.9.1",
"multer": "^1.4.5-lts.1",
Expand Down
40 changes: 24 additions & 16 deletions packages/server/src/libs/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,49 @@ import mongoose from 'mongoose';
import { logger } from './logger.js';
import Config from '../config/index.js';

// Return the connection if it has already been established
async function getDatabase() {
if (
[mongoose.STATES.connected, mongoose.STATES.connecting].includes(
mongoose.connection.readyState,
)
) {
return mongoose.connection;
}

return mongoose.connect(Config.DB_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
});
}

export async function connectDB() {
try {
// Return the connection if it has already been established
if ([1, 2].includes(mongoose.connection.readyState)) {
return mongoose.connection;
}

logger.info(`[pid: ${process.pid}] Connecting to MongoDB database...`);

const mongooseInstance = await mongoose.connect(Config.DB_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
});
const dbInstance = await getDatabase();

const db = mongooseInstance.connection;
const { connection } = dbInstance;

logger.info(
`[pid: ${process.pid}] Successfully connected to MongoDB database`,
);

db.on('error', (error) => {
connection.on('error', (error) => {
logger.error(error);
});

db.once('disconnected', () => {
connection.once('disconnected', () => {
logger.warn(`[pid: ${process.pid}]: Disconnected from MongoDB database`);
});

db.on('reconnected', () => {
connection.on('reconnected', () => {
logger.info(`[pid: ${process.pid}]: Reconnected to MongoDB database`);
});

return db;
return connection;
} catch (error) {
logger.error(error);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ describe('PUT /users/me', () => {
expect(response.status).toBe(422);
});

it('Should return status 404 and en expected message for not found user', async () => {
it("Should return status 404 and an expected message if didn't find the user", async () => {
const { sessionCookie, currentUser } = await signUpRequest(global.app);

await User.deleteOne({ _id: currentUser.id });
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/tests/jest.setup-after-env.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ beforeAll(async () => {
});

beforeEach(async () => {
await mongoose.connections[0].dropDatabase();
await mongoose.connection.dropDatabase();
});

afterAll(async () => {
await mongoose.connections[0].close();
await mongoose.connection.close();
});
103 changes: 51 additions & 52 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 306e9fd

Please sign in to comment.