Skip to content

Commit

Permalink
Added a single mongo session for whole application
Browse files Browse the repository at this point in the history
  • Loading branch information
Community-Programmer committed Jan 9, 2024
1 parent 0899228 commit c8f2dd3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 4 deletions.
6 changes: 6 additions & 0 deletions src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import mongoose from "mongoose";
import { MONGO_DB_URL } from "./constants";
import { logger } from "./libraries";

let session!: mongoose.ClientSession;

export const connect = async (): Promise<void> => {
try {
await mongoose.connect(MONGO_DB_URL as string, {
Expand All @@ -10,6 +12,7 @@ export const connect = async (): Promise<void> => {
useFindAndModify: false,
useNewUrlParser: true,
});
session = await mongoose.startSession();
} catch (error: unknown) {
if (error instanceof Error) {
const errorMessage = error.toString();
Expand Down Expand Up @@ -45,5 +48,8 @@ export const connect = async (): Promise<void> => {
};

export const disconnect = async (): Promise<void> => {
session?.endSession();
await mongoose.connection.close();
};

export { session };
6 changes: 2 additions & 4 deletions src/resolvers/Mutation/createEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { isValidString } from "../../libraries/validators/validateString";
import { compareDates } from "../../libraries/validators/compareDates";
import { EventAttendee } from "../../models/EventAttendee";
import { cacheEvents } from "../../services/EventCache/cacheEvents";
import mongoose from "mongoose";
import type mongoose from "mongoose";
import { session } from "../../db";

/**
* This function enables to create an event.
Expand Down Expand Up @@ -120,7 +121,6 @@ export const createEvent: MutationResolvers["createEvent"] = async (
);
}

const session = await mongoose.startSession();
session.startTransaction();

try {
Expand Down Expand Up @@ -151,7 +151,6 @@ export const createEvent: MutationResolvers["createEvent"] = async (
}

await session.commitTransaction();
session.endSession();

if (!createdEvent) {
throw new Error(requestContext.translate("Failed to create event!"));
Expand All @@ -161,7 +160,6 @@ export const createEvent: MutationResolvers["createEvent"] = async (
return createdEvent[0].toObject();
} catch (error) {
await session.abortTransaction();
session.endSession();
throw error;
}
/* Commenting out this notification code coz we don't use firebase anymore.
Expand Down

0 comments on commit c8f2dd3

Please sign in to comment.