ユーザーアイコン

mizuko

約1か月前

0
0

Microsoft Graph API Subscriptionの仕様と実装方法

Microsoft Graph API
Outlook

Microsoft Graph APIのSubscription機能はリソースの変更通知を受け取るための仕組みで、Gmail APIとは異なり更新が可能な点が特徴。

Subscription作成

const subscription = { changeType: 'created,updated', notificationUrl: 'https://example.com/webhook', resource: 'me/messages', expirationDateTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString(), clientState: 'secretClientState' }; const response = await client.api('/subscriptions').post(subscription); // response: { id: "subscription-id", expirationDateTime: "...", ... }

Webhook通知の形式

{ "value": [ { "subscriptionId": "subscription-id", "clientState": "secretClientState", "changeType": "created", "resource": "me/messages/AAMkADk0...", "resourceData": { "@odata.type": "#Microsoft.Graph.Message", "@odata.id": "messages/AAMkADk0..." } } ] }

subscriptionIdを使用してユーザーを識別し、resourceから変更されたリソースのIDを取得する。

Subscriptionの更新(Gmail APIとの大きな違い)

// 有効期限を延長(subscriptionIdを維持) const update = { expirationDateTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString() }; await client.api(`/subscriptions/${subscriptionId}`).patch(update);

Gmail APIのWatchは更新不可で削除→再作成が必要だが、Microsoft Graph APIはPATCHで更新可能。

有効期限の管理

  • メールSubscriptionは最大4230分(約3日)有効
  • 期限切れ前(推奨:24時間前)に更新処理を実行
  • 更新によりsubscriptionIdを保持できるため、管理が簡潔

実装上の考慮点

  • 期限が近い場合は更新、期限切れの場合のみ削除→再作成
  • YAGNIの原則に従い、更新が不要なリソースではupsert処理を避ける

参照: https://learn.microsoft.com/en-us/graph/api/resources/subscription