Skip to content

Instantly share code, notes, and snippets.

@CreatiCoding
Created August 31, 2024 07:26
Show Gist options
  • Save CreatiCoding/75cb6f4c646a5934188fc21621e3d65d to your computer and use it in GitHub Desktop.
Save CreatiCoding/75cb6f4c646a5934188fc21621e3d65d to your computer and use it in GitHub Desktop.
Google Calendar List API w/Node.js SDK
import * as calendar from "@googleapis/calendar";
import { format, subDays, addDays, toDate } from "date-fns";
const auth = new calendar.auth.GoogleAuth({
credentials: {
client_email: process.env.GOOGLE_CLIENT_EMAIL,
private_key: process.env.GOOGLE_PRIVATE_KEY
},
scopes: ["https://www.googleapis.com/auth/calendar.readonly"],
});
export async function getCalendarEvents({
calendarId,
from,
to,
pageSize,
}: {
calendarId: string;
from?: Date;
to?: Date;
pageSize?: number;
}) {
console.log({ calendar });
const calendarClient = calendar.calendar({
version: "v3",
auth,
});
const timeMin = subDays(new Date(), 30).toISOString();
const timeMax = addDays(new Date(), 30).toISOString();
const res = await calendarClient.events.list({
calendarId,
timeMin: from ? from.toISOString() : timeMin,
timeMax: to ? to.toISOString() : timeMax,
maxResults: pageSize ?? 1000,
singleEvents: true,
});
const data = (res.data?.items ?? [])
.filter((x) => x.status !== "cancelled")
.map((x) => {
const startDate = toDate(x?.start?.dateTime!);
const endDate = toDate(x?.end?.dateTime!);
return {
name: x.summary || "No title",
startDate: format(startDate, "yyyy-MM-dd"),
endDate: format(endDate, "yyyy-MM-dd"),
startTime: format(startDate, "HH:mm"),
endTime: format(endDate, "HH:mm"),
};
});
data.sort((a, b) => {
return new Date(a.startDate).getTime() - new Date(b.startDate).getTime();
});
return data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment