fix: replace all async foreach callbacks (#10157)

Co-authored-by: zomars <zomars@me.com>
fix/storybook-builds^2
nicktrn 2023-08-26 01:43:10 +01:00 committed by GitHub
parent 83aea7d28c
commit c1bcfcfa3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 266 additions and 240 deletions

View File

@ -158,9 +158,10 @@ test.describe("pro user", () => {
await expect(page.locator("[data-testid=success-page]")).toBeVisible();
additionalGuests.forEach(async (email) => {
const promises = additionalGuests.map(async (email) => {
await expect(page.locator(`[data-testid="attendee-email-${email}"]`)).toHaveText(email);
});
await Promise.all(promises);
});
test("Time slots should be reserved when selected", async ({ context, page }) => {

View File

@ -121,18 +121,21 @@ const Reschedule = async (bookingUid: string, cancellationReason: string) => {
const bookingRefsFiltered: BookingReference[] = bookingToReschedule.references.filter(
(ref) => !!credentialsMap.get(ref.type)
);
try {
bookingRefsFiltered.forEach(async (bookingRef) => {
if (bookingRef.uid) {
const promises = bookingRefsFiltered.map(async (bookingRef) => {
if (!bookingRef.uid) return;
if (bookingRef.type.endsWith("_calendar")) {
const calendar = await getCalendar(credentialsMap.get(bookingRef.type));
return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent);
} else if (bookingRef.type.endsWith("_video")) {
return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);
}
}
});
try {
await Promise.all(promises);
} catch (error) {
// FIXME: error logging - non-Error type errors are currently discarded
if (error instanceof Error) {
logger.error(error.message);
}

View File

@ -121,17 +121,19 @@ const Reschedule = async (bookingUid: string, cancellationReason: string) => {
const bookingRefsFiltered: BookingReference[] = bookingToReschedule.references.filter(
(ref) => !!credentialsMap.get(ref.type)
);
try {
bookingRefsFiltered.forEach(async (bookingRef) => {
if (bookingRef.uid) {
const promises = bookingRefsFiltered.map(async (bookingRef) => {
if (!bookingRef.uid) return;
if (bookingRef.type.endsWith("_calendar")) {
const calendar = await getCalendar(credentialsMap.get(bookingRef.type));
return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent);
} else if (bookingRef.type.endsWith("_video")) {
return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);
}
}
});
try {
await Promise.all(promises);
} catch (error) {
if (error instanceof Error) {
logger.error(error.message);

View File

@ -10,6 +10,7 @@ export async function scheduleTrigger(
) {
try {
//schedule job to call subscriber url at the end of meeting
// FIXME: in-process scheduling - job will vanish on server crash / restart
const job = schedule.scheduleJob(
`${subscriber.appId}_${subscriber.id}`,
booking.endTime,
@ -57,11 +58,10 @@ export async function cancelScheduledJobs(
appId?: string | null,
isReschedule?: boolean
) {
try {
let scheduledJobs = booking.scheduledJobs || [];
if (!booking.scheduledJobs) return;
if (booking.scheduledJobs) {
booking.scheduledJobs.forEach(async (scheduledJob) => {
let scheduledJobs = booking.scheduledJobs || [];
const promises = booking.scheduledJobs.map(async (scheduledJob) => {
if (appId) {
if (scheduledJob.startsWith(appId)) {
if (schedule.scheduledJobs[scheduledJob]) {
@ -88,7 +88,9 @@ export async function cancelScheduledJobs(
});
}
});
}
try {
await Promise.all(promises);
} catch (error) {
console.error("Error cancelling scheduled jobs", error);
}

View File

@ -12,7 +12,7 @@ const libraries = [
},
];
libraries.forEach(async (lib) => {
const promises = libraries.map(async (lib) => {
await build({
build: {
outDir: `./dist/${lib.fileName}`,
@ -29,3 +29,4 @@ libraries.forEach(async (lib) => {
},
});
});
await Promise.all(promises);

View File

@ -430,9 +430,9 @@ async function handler(req: CustomRequest) {
bookingToDelete.recurringEventId &&
allRemainingBookings
) {
bookingToDelete.user.credentials
const promises = bookingToDelete.user.credentials
.filter((credential) => credential.type.endsWith("_calendar"))
.forEach(async (credential) => {
.map(async (credential) => {
const calendar = await getCalendar(credential);
for (const updBooking of updatedBookings) {
const bookingRef = updBooking.references.find((ref) => ref.type.includes("_calendar"));
@ -443,6 +443,13 @@ async function handler(req: CustomRequest) {
}
}
});
try {
await Promise.all(promises);
} catch (error) {
if (error instanceof Error) {
logger.error(error.message);
}
}
} else {
apiDeletes.push(calendar?.deleteEvent(uid, evt, externalCalendarId) as Promise<unknown>);
}
@ -603,11 +610,13 @@ async function handler(req: CustomRequest) {
});
// delete scheduled jobs of cancelled bookings
// FIXME: async calls into ether
updatedBookings.forEach((booking) => {
cancelScheduledJobs(booking);
});
//Workflows - cancel all reminders for cancelled bookings
// FIXME: async calls into ether
updatedBookings.forEach((booking) => {
booking.workflowReminders.forEach((reminder) => {
if (reminder.method === WorkflowMethods.EMAIL) {
@ -622,11 +631,14 @@ async function handler(req: CustomRequest) {
const prismaPromises: Promise<unknown>[] = [bookingReferenceDeletes];
// @TODO: find a way in the future if a promise fails don't stop the rest of the promises
// Also if emails fails try to requeue them
try {
await Promise.all(prismaPromises.concat(apiDeletes));
const settled = await Promise.allSettled(prismaPromises.concat(apiDeletes));
const rejected = settled.filter(({ status }) => status === "rejected") as PromiseRejectedResult[];
if (rejected.length) {
throw new Error(`Reasons: ${rejected.map(({ reason }) => reason)}`);
}
// TODO: if emails fail try to requeue them
await sendCancelledEmails(evt, { eventName: bookingToDelete?.eventType?.eventName });
} catch (error) {
console.error("Error deleting event", error);

View File

@ -102,7 +102,8 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
throw new TRPCError({ code: "FORBIDDEN", message: "User isn't owner of the current booking" });
}
if (bookingToReschedule) {
if (!bookingToReschedule) return;
let event: Partial<EventType> = {};
if (bookingToReschedule.eventTypeId) {
event = await prisma.eventType.findFirstOrThrow({
@ -130,9 +131,11 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
});
// delete scheduled jobs of previous booking
// FIXME: async fn off into the ether
cancelScheduledJobs(bookingToReschedule);
//cancel workflow reminders of previous booking
// FIXME: more async fns off into the ether
bookingToReschedule.workflowReminders.forEach((reminder) => {
if (reminder.method === WorkflowMethods.EMAIL) {
deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
@ -146,10 +149,7 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
const [mainAttendee] = bookingToReschedule.attendees;
// @NOTE: Should we assume attendees language?
const tAttendees = await getTranslation(mainAttendee.locale ?? "en", "common");
const usersToPeopleType = (
users: PersonAttendeeCommonFields[],
selectedLanguage: TFunction
): Person[] => {
const usersToPeopleType = (users: PersonAttendeeCommonFields[], selectedLanguage: TFunction): Person[] => {
return users?.map((user) => {
return {
email: user.email || "",
@ -198,17 +198,20 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
const bookingRefsFiltered: BookingReference[] = bookingToReschedule.references.filter((ref) =>
credentialsMap.has(ref.type)
);
bookingRefsFiltered.forEach(async (bookingRef) => {
if (bookingRef.uid) {
// FIXME: error-handling
await Promise.allSettled(
bookingRefsFiltered.map(async (bookingRef) => {
if (!bookingRef.uid) return;
if (bookingRef.type.endsWith("_calendar")) {
const calendar = await getCalendar(credentialsMap.get(bookingRef.type));
return calendar?.deleteEvent(bookingRef.uid, builder.calendarEvent, bookingRef.externalCalendarId);
} else if (bookingRef.type.endsWith("_video")) {
return deleteMeeting(credentialsMap.get(bookingRef.type), bookingRef.uid);
}
}
});
})
);
// Send emails
await sendRequestRescheduleEmail(builder.calendarEvent, {
@ -234,8 +237,7 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
),
uid: bookingToReschedule?.uid,
location: bookingToReschedule?.location,
destinationCalendar:
bookingToReschedule?.destinationCalendar || bookingToReschedule?.destinationCalendar,
destinationCalendar: bookingToReschedule?.destinationCalendar || bookingToReschedule?.destinationCalendar,
cancellationReason: `Please reschedule. ${cancellationReason}`, // TODO::Add i18-next for this
};
@ -268,5 +270,4 @@ export const requestRescheduleHandler = async ({ ctx, input }: RequestReschedule
})
);
await Promise.all(promises);
}
};

View File

@ -264,13 +264,13 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
},
});
steps.forEach(async (step) => {
const promiseSteps = steps.map(async (step) => {
if (
step.action !== WorkflowActions.SMS_ATTENDEE &&
step.action !== WorkflowActions.WHATSAPP_ATTENDEE
) {
//as we do not have attendees phone number (user is notified about that when setting this action)
bookingsForReminders.forEach(async (booking) => {
const promiseScheduleReminders = bookingsForReminders.map(async (booking) => {
const defaultLocale = "en";
const bookingInfo = {
uid: booking.uid,
@ -367,29 +367,28 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
);
}
});
await Promise.all(promiseScheduleReminders);
}
});
await Promise.all(promiseSteps);
}
//create all workflow - eventtypes relationships
activeOnEventTypes.forEach(async (eventType) => {
await ctx.prisma.workflowsOnEventTypes.createMany({
data: {
data: activeOnEventTypes.map((eventType) => ({
workflowId: id,
eventTypeId: eventType.id,
},
})),
});
if (eventType.children.length) {
eventType.children.forEach(async (chEventType) => {
await ctx.prisma.workflowsOnEventTypes.createMany({
data: {
await Promise.all(
activeOnEventTypes.map((eventType) =>
ctx.prisma.workflowsOnEventTypes.createMany({
data: eventType.children.map((chEventType) => ({
workflowId: id,
eventTypeId: chEventType.id,
},
});
});
}
});
})),
})
)
);
}
userWorkflow.steps.map(async (oldStep) => {
@ -465,11 +464,14 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
});
//cancel all workflow reminders from steps that were edited
remindersToUpdate.forEach(async (reminder) => {
// FIXME: async calls into ether
remindersToUpdate.forEach((reminder) => {
if (reminder.method === WorkflowMethods.EMAIL) {
deleteScheduledEmailReminder(reminder.id, reminder.referenceId);
} else if (reminder.method === WorkflowMethods.SMS) {
deleteScheduledSMSReminder(reminder.id, reminder.referenceId);
} else if (reminder.method === WorkflowMethods.WHATSAPP) {
deleteScheduledWhatsappReminder(reminder.id, reminder.referenceId);
}
});
const eventTypesToUpdateReminders = activeOn.filter((eventTypeId) => {
@ -497,7 +499,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
user: true,
},
});
bookingsOfEventTypes.forEach(async (booking) => {
const promiseScheduleReminders = bookingsOfEventTypes.map(async (booking) => {
const defaultLocale = "en";
const bookingInfo = {
uid: booking.uid,
@ -594,6 +596,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
);
}
});
await Promise.all(promiseScheduleReminders);
}
}
});
@ -617,7 +620,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
return activeEventType;
}
});
addedSteps.forEach(async (step) => {
const promiseAddedSteps = addedSteps.map(async (step) => {
if (step) {
const { senderName, ...newStep } = step;
newStep.sender = getSender({
@ -749,6 +752,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
}
}
});
await Promise.all(promiseAddedSteps);
}
//update trigger, name, time, timeUnit