From adf012643a293bb8960c207c300284476c7cc1f2 Mon Sep 17 00:00:00 2001 From: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com> Date: Wed, 6 Dec 2023 21:10:25 +0400 Subject: [PATCH] fix: '/slots' endpoint API fixes (#12693) --- apps/api/pages/api/slots/_get.ts | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/apps/api/pages/api/slots/_get.ts b/apps/api/pages/api/slots/_get.ts index 6393bc79c1ee11..61447e1751dbd7 100644 --- a/apps/api/pages/api/slots/_get.ts +++ b/apps/api/pages/api/slots/_get.ts @@ -1,5 +1,9 @@ +import timezone from "dayjs/plugin/timezone"; +import utc from "dayjs/plugin/utc"; import type { NextApiRequest, NextApiResponse } from "next"; +import dayjs from "@calcom/dayjs"; +import { isSupportedTimeZone } from "@calcom/lib/date-fns"; import { HttpError } from "@calcom/lib/http-error"; import { defaultResponder } from "@calcom/lib/server"; import { createContext } from "@calcom/trpc/server/createContext"; @@ -9,10 +13,34 @@ import { getAvailableSlots } from "@calcom/trpc/server/routers/viewer/slots/util import { TRPCError } from "@trpc/server"; import { getHTTPStatusCodeFromError } from "@trpc/server/http"; +// Apply plugins +dayjs.extend(utc); +dayjs.extend(timezone); + async function handler(req: NextApiRequest, res: NextApiResponse) { try { - const input = getScheduleSchema.parse(req.query); - return await getAvailableSlots({ ctx: await createContext({ req, res }), input }); + const { usernameList, ...rest } = req.query; + let slugs = usernameList; + if (!Array.isArray(usernameList)) { + slugs = usernameList ? [usernameList] : []; + } + const input = getScheduleSchema.parse({ usernameList: slugs, ...rest }); + const timeZoneSupported = input.timeZone ? isSupportedTimeZone(input.timeZone) : false; + const availableSlots = await getAvailableSlots({ ctx: await createContext({ req, res }), input }); + const slotsInProvidedTimeZone = timeZoneSupported + ? Object.keys(availableSlots.slots).reduce( + (acc: Record, date) => { + acc[date] = availableSlots.slots[date].map((slot) => ({ + ...slot, + time: dayjs(slot.time).tz(input.timeZone).format(), + })); + return acc; + }, + {} + ) + : availableSlots; + + return slotsInProvidedTimeZone; // eslint-disable-next-line @typescript-eslint/no-explicit-any } catch (cause) { if (cause instanceof TRPCError) {