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

Create weekly event recurring instance #1658

Merged
merged 10 commits into from
Jan 17, 2024
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 };
175 changes: 143 additions & 32 deletions src/resolvers/Mutation/createEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import { compareDates } from "../../libraries/validators/compareDates";
import { EventAttendee } from "../../models/EventAttendee";
import { cacheEvents } from "../../services/EventCache/cacheEvents";
import type mongoose from "mongoose";
import { session } from "../../db";

/**
* This function enables to create an event.
Expand Down Expand Up @@ -119,49 +121,56 @@
);
}

// Creates new event.
const createdEvent = await Event.create({
...args.data,
creator: currentUser._id,
admins: [currentUser._id],
organization: organization._id,
});
session.startTransaction();

if (createdEvent !== null) {
await cacheEvents([createdEvent]);
}
try {
let createdEvent;

await EventAttendee.create({
userId: currentUser._id.toString(),
eventId: createdEvent._id,
});
if (

Check warning on line 129 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L125-L129

Added lines #L125 - L129 were not covered by tests
!args.data?.recurring ||
(args.data?.recurring && args.data?.recurrance == "ONCE")

Check warning on line 131 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L131

Added line #L131 was not covered by tests
) {
createdEvent = await generateOnetimeEvent(
args,
currentUser,
organization,
session
);
} else {
//Cases for DAILY, WEEKLY, MONTHLY AND YEARLY recurring events
switch (args.data?.recurrance) {
case "WEEKLY":
createdEvent = await generateWeeklyRecurringInstances(
args,
currentUser,
organization,
session
);
break;
}

Check warning on line 150 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L133-L150

Added lines #L133 - L150 were not covered by tests
}

/*
Adds createdEvent._id to eventAdmin, createdEvents and registeredEvents lists
on currentUser's document.
*/
await User.updateOne(
{
_id: currentUser._id,
},
{
$push: {
eventAdmin: createdEvent._id,
createdEvents: createdEvent._id,
registeredEvents: createdEvent._id,
},
await session.commitTransaction();

if (!createdEvent) {
throw new Error(requestContext.translate("Failed to create event!"));
}
);

// Returns the createdEvent.
return createdEvent[0].toObject();
} catch (error) {
await session.abortTransaction();
throw error;
}
/* Commenting out this notification code coz we don't use firebase anymore.

for (let i = 0; i < organization.members.length; i++) {

Check warning on line 167 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L153-L167

Added lines #L153 - L167 were not covered by tests
const user = await User.findOne({
_id: organization.members[i],
}).lean();



Check warning on line 173 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L172-L173

Added lines #L172 - L173 were not covered by tests
// Checks whether both user and user.token exist.
if (user && user.token) {
await admin.messaging().send({
Expand All @@ -173,8 +182,110 @@
});
}
}
*/

Check warning on line 185 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L185

Added line #L185 was not covered by tests

// Returns the createdEvent.
return createdEvent.toObject();
};

async function associateEventWithUser(
currentUser: any,
createdEvent: any,
session: mongoose.ClientSession
) {
await EventAttendee.create(
[
{
userId: currentUser._id.toString(),
eventId: createdEvent._id,
},
],
{ session }
);

await User.updateOne(
{
_id: currentUser._id,
},
{
$push: {
eventAdmin: createdEvent._id,
createdEvents: createdEvent._id,
registeredEvents: createdEvent._id,
},
},
{ session }
);
}

export async function generateOnetimeEvent(
args: any,
currentUser: any,
organization: any,
session: mongoose.ClientSession
) {
const createdEvent = await Event.create(
[
{
...args.data,
creator: currentUser._id,
admins: [currentUser._id],
organization: organization._id,
},
],
{ session }
);

if (createdEvent !== null) {
await cacheEvents([createdEvent[0]]);
}

await associateEventWithUser(currentUser, createdEvent[0], session);

return createdEvent;
}

Check warning on line 243 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L188-L243

Added lines #L188 - L243 were not covered by tests

export async function generateWeeklyRecurringInstances(
args: any,
currentUser: any,
organization: any,
session: mongoose.ClientSession
) {
const recurringEvents = [];
const { data } = args;

const startDate = new Date(data?.startDate);
const endDate = new Date(data?.endDate);

while (startDate <= endDate) {
const recurringEventData = {
...data,
startDate: new Date(startDate),
};

const createdEvent = {
...recurringEventData,
creator: currentUser._id,
admins: [currentUser._id],
organization: organization._id,
};

recurringEvents.push(createdEvent);

startDate.setDate(startDate.getDate() + 7);
}

//Bulk insertion in database
const createdEvents = await Event.insertMany(recurringEvents, { session });

const eventsArray = Array.isArray(createdEvents)
? createdEvents
: [createdEvents];

for (const createdEvent of eventsArray) {
await associateEventWithUser(currentUser, createdEvent, session);

if (createdEvent !== null) {
await cacheEvents([createdEvent]);
}
}

return eventsArray;
}

Check warning on line 291 in src/resolvers/Mutation/createEvent.ts

View check run for this annotation

Codecov / codecov/patch

src/resolvers/Mutation/createEvent.ts#L245-L291

Added lines #L245 - L291 were not covered by tests
Loading
Loading