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 };
63 changes: 63 additions & 0 deletions src/helpers/eventInstance.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import type mongoose from "mongoose";
import { Event } from "../models";

//Function for creating single events

export async function generateSingleEvent(
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 }
);

return createdEvent;
}

//Function for creating Weekly events

export async function generateWeeklyEvents(
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);
Community-Programmer marked this conversation as resolved.
Show resolved Hide resolved

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 weeklyEvents = await Event.insertMany(recurringEvents, { session });

return Array.isArray(weeklyEvents) ? weeklyEvents : [weeklyEvents];
}
129 changes: 85 additions & 44 deletions src/resolvers/Mutation/createEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@ import { isValidString } from "../../libraries/validators/validateString";
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";
import {
generateSingleEvent,
generateWeeklyEvents,
} from "../../helpers/eventInstance";

/**
* This function enables to create an event.
Expand Down Expand Up @@ -119,27 +125,86 @@ export const createEvent: MutationResolvers["createEvent"] = async (
);
}

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

try {
let createdEvent!: any;

if (args.data?.recurring) {
switch (args.data?.recurrance) {
case "ONCE":
createdEvent = await generateSingleEvent(
args,
currentUser,
organization,
session
);

for (const event of createdEvent) {
await associateEventWithUser(currentUser, event, session);
await cacheEvents([event]);
}

break;

case "WEEKLY":
createdEvent = await generateWeeklyEvents(
args,
currentUser,
organization,
session
);

for (const event of createdEvent) {
await associateEventWithUser(currentUser, event, session);
await cacheEvents([event]);
}

break;
}
} else {
createdEvent = await generateSingleEvent(
args,
currentUser,
organization,
session
);

for (const event of createdEvent) {
await associateEventWithUser(currentUser, event, session);
await cacheEvents([event]);
}
}

if (session) {
await session.commitTransaction();
}

if (createdEvent !== null) {
await cacheEvents([createdEvent]);
// Returns the createdEvent.
return createdEvent[0].toObject();
} catch (error) {
await session.abortTransaction();
throw error;
}
};

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

/*
Adds createdEvent._id to eventAdmin, createdEvents and registeredEvents lists
on currentUser's document.
*/
await User.updateOne(
{
_id: currentUser._id,
Expand All @@ -150,31 +215,7 @@ export const createEvent: MutationResolvers["createEvent"] = async (
createdEvents: createdEvent._id,
registeredEvents: createdEvent._id,
},
}
},
{ session }
);

/* Commenting out this notification code coz we don't use firebase anymore.

for (let i = 0; i < organization.members.length; i++) {
const user = await User.findOne({
_id: organization.members[i],
}).lean();



// Checks whether both user and user.token exist.
if (user && user.token) {
await admin.messaging().send({
token: user.token,
notification: {
title: "New Event",
body: `${currentUser.firstName} has created a new event in ${organization.name}`,
},
});
}
}
*/

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