The Node.js® Website
1'use strict';
2
3import {
4 BASE_CALENDAR_URL,
5 SHARED_CALENDAR_KEY,
6} from './next.calendar.constants.mjs';
7
8/**
9 *
10 * @param {string} calendarId
11 * @param {number} maxResults
12 * @returns {Promise<Array<import('./types').CalendarEvent>>}
13 */
14export const getCalendarEvents = async (calendarId = '', maxResults = 20) => {
15 const currentDate = new Date();
16 const nextWeekDate = new Date();
17
18 nextWeekDate.setDate(currentDate.getDate() + 7);
19
20 const calendarQueryParams = new URLSearchParams({
21 calendarId,
22 maxResults,
23 singleEvents: true,
24 timeZone: 'Etc/Utc',
25 key: SHARED_CALENDAR_KEY,
26 timeMax: nextWeekDate.toISOString(),
27 timeMin: currentDate.toISOString(),
28 });
29
30 const calendarQueryUrl = new URL(`${BASE_CALENDAR_URL}${calendarId}/events`);
31
32 calendarQueryParams.forEach((value, key) =>
33 calendarQueryUrl.searchParams.append(key, value)
34 );
35
36 return fetch(calendarQueryUrl.toString())
37 .then(response => response.json())
38 .then(calendar => calendar.items);
39};