( accessToken: string, calendarId: string, config: GoogleCalendarWebhookConfig, requestId: string, logger: Logger )
| 183 | } |
| 184 | |
| 185 | async function fetchChangedEvents( |
| 186 | accessToken: string, |
| 187 | calendarId: string, |
| 188 | config: GoogleCalendarWebhookConfig, |
| 189 | requestId: string, |
| 190 | logger: Logger |
| 191 | ): Promise<CalendarEvent[]> { |
| 192 | const allEvents: CalendarEvent[] = [] |
| 193 | const maxEvents = config.maxEventsPerPoll || MAX_EVENTS_PER_POLL |
| 194 | let pageToken: string | undefined |
| 195 | let pages = 0 |
| 196 | |
| 197 | do { |
| 198 | pages++ |
| 199 | const params = new URLSearchParams({ |
| 200 | updatedMin: config.lastCheckedTimestamp!, |
| 201 | singleEvents: 'true', |
| 202 | showDeleted: 'true', |
| 203 | maxResults: String(Math.min(maxEvents, 250)), |
| 204 | }) |
| 205 | |
| 206 | if (pageToken) { |
| 207 | params.set('pageToken', pageToken) |
| 208 | } |
| 209 | |
| 210 | if (config.searchTerm) { |
| 211 | params.set('q', config.searchTerm) |
| 212 | } |
| 213 | |
| 214 | const encodedCalendarId = encodeURIComponent(calendarId) |
| 215 | const url = `${CALENDAR_API_BASE}/calendars/${encodedCalendarId}/events?${params.toString()}` |
| 216 | |
| 217 | const response = await fetch(url, { |
| 218 | headers: { Authorization: `Bearer ${accessToken}` }, |
| 219 | }) |
| 220 | |
| 221 | if (!response.ok) { |
| 222 | const status = response.status |
| 223 | const errorData = await response.json().catch(() => ({})) |
| 224 | |
| 225 | if (status === 403 || status === 429) { |
| 226 | throw new Error( |
| 227 | `Calendar API rate limit (${status}) — skipping to retry next poll cycle: ${JSON.stringify(errorData)}` |
| 228 | ) |
| 229 | } |
| 230 | |
| 231 | throw new Error(`Failed to fetch calendar events: ${status} - ${JSON.stringify(errorData)}`) |
| 232 | } |
| 233 | |
| 234 | const data = await response.json() |
| 235 | const events = (data.items || []) as CalendarEvent[] |
| 236 | allEvents.push(...events) |
| 237 | |
| 238 | pageToken = data.nextPageToken as string | undefined |
| 239 | |
| 240 | // Stop if we have enough events or hit the page limit |
| 241 | if (allEvents.length >= maxEvents || pages >= MAX_PAGES) { |
| 242 | break |
no test coverage detected