ユーザーアイコン

mizuko

2か月前

0
0

Google Calendar Watch API を使用した変更通知の受信方法

バックエンド
Google Calendar API
Webhook

Google Calendar API の Watch 機能を使用して、カレンダーの変更をリアルタイムで受信する。

  1. Watch チャンネルの作成

    const watchRequest = { id: channelId, // UUID v4 type: 'web_hook', address: 'https://api.example.com/calendar-webhook/google', token: 'target=translead-crm', expiration: String(Date.now() + 7 * 24 * 60 * 60 * 1000) // 文字列として }; const response = await calendar.events.watch({ calendarId: 'primary', requestBody: watchRequest });
  2. 通知の受信

    // ヘッダーの型定義 interface GoogleCalendarNotificationHeaders { 'x-goog-channel-id': string; 'x-goog-resource-state': string; 'x-goog-resource-id': string; } // sync 以外の通知で同期処理を開始 if (headers['x-goog-resource-state'] !== 'sync') { await this.calendarSyncService.syncFromGoogleCalendar(channelId, resourceId); }
  3. チャンネルの管理

    • 有効期限(最大7日)前に再作成が必要
    • 不要になったら channels.stop() で停止