fix: main google calendar not being connected (#17404)

This commit is contained in:
Benny Joo
2024-10-30 11:58:44 +00:00
committed by GitHub
parent 2784564427
commit aaa5531a3a
@@ -1,4 +1,4 @@
import type { Auth } from "googleapis";
import type { Auth, calendar_v3 } from "googleapis";
import { google } from "googleapis";
import type { NextApiRequest, NextApiResponse } from "next";
@@ -72,16 +72,12 @@ async function getHandler(req: NextApiRequest, res: NextApiResponse) {
auth: oAuth2Client,
});
const cals = await calendar.calendarList.list({ fields: "items(id,summary,primary,accessRole)" });
const tokenInfo = key.access_token ? await oAuth2Client.getTokenInfo(key.access_token) : null;
const userEmail = tokenInfo?.email ?? null;
const cals = await getAllCalendars(calendar);
let primaryCal = cals.data.items?.find(
(cal) => cal.primary || cal.accessRole === "owner" || cal.id === userEmail
);
let primaryCal = cals.find((cal) => cal.primary);
if (!primaryCal?.id) {
// If the primary calendar is not set, set it to the first calendar
primaryCal = cals.data.items?.[0];
primaryCal = cals[0];
}
// Only attempt to update the user's profile photo if the user has granted the required scope
@@ -208,6 +204,24 @@ async function updateProfilePhoto(oAuth2Client: Auth.OAuth2Client, userId: numbe
}
}
async function getAllCalendars(calendar: calendar_v3.Calendar) {
let allCalendars: calendar_v3.Schema$CalendarListEntry[] = [];
let pageToken = null;
do {
const response: any = await calendar.calendarList.list({
fields: "items(id,summary,primary,accessRole),nextPageToken",
pageToken: pageToken,
maxResults: 250, // 250 is max
});
allCalendars = [...allCalendars, ...(response.data.items ?? [])];
pageToken = response.data.nextPageToken;
} while (pageToken);
return allCalendars;
}
export default defaultHandler({
GET: Promise.resolve({ default: defaultResponder(getHandler) }),
});