メインコンテンツまでスキップ

Webhooks(Webhook)

Webhook は、ある Web アプリケーションが別の Web アプリケーションと通信できるようにする、イベント駆動アーキテクチャの一種です。

Webhook は、ユーザー定義の HTTP callback(コールバック)のように機能し、データベース内での新規レコード作成、バグトラッカー上の issue のステータス変更、チャットアプリケーションでの新規メッセージなどのイベントによってトリガーされます。

イベントが発生すると、ソースシステムは Webhook で指定された URL に HTTP リクエストを送信し、Webhook と関連するコードの実行が開始されます。HTTP リクエストの payload(ペイロード)には通常、イベントに関連するデータが含まれており、受信側システムはそれを利用して追加のアクションを実行できます。

また、Webhook で定義された URL にアクセスすることで Webhook を呼び出すこともできます。Squid を使うと、Webhook を公開し、内部および外部の他サービスからアクセス可能にできます。

Webhook の作成

Webhook を定義するには、SquidService クラスを拡張したクラス内の関数に @webhook decorator(デコレーター)を付与するだけです。

Backend code
import { SquidService, webhook, WebhookRequest, WebhookResponse } from '@squidcloud/backend';

export class ExampleService extends SquidService {
@webhook('handleStripePayment')
handleStripePayment(request: WebhookRequest): Promise<WebhookResponse | any> {
// TODO - add your business logic here
// You can use this.createWebhookResponse(...) to create a response.
}
}

Webhook URL は次の形式になります。

https://[YOUR_APP_ID].[APP_REGION].squid.cloud/webhooks/[WEBHOOK_ID]

たとえば、handleStripePayment Webhook は次の URL を公開します。

https://[YOUR_APP_ID].[APP_REGION].squid.cloud/webhooks/handleStripePayment

ローカル開発時は、次の URL で Webhook にアクセスできます。

https://[YOUR_APP_ID]-dev-[YOUR_SQUID_DEVELOPER_ID].[APP_REGION].squid.cloud/webhooks/handleStripePayment

dev 環境にデプロイされた Webhook を使用する場合は、次の URL で Webhook にアクセスできます。

https://[YOUR_APP_ID]-dev.[APP_REGION].squid.cloud/webhooks/handleStripePayment

request オブジェクトは、query parameters、body、headers などを含む完全な HTTP context を提供します。

次のサンプルコードは、Squid の backend SDK を使用して Squid AI Agent を API に変換する例で、Squid Client SDK を使用する代わりになります。

Backend code
import { secureAiAgent, SquidService, webhook } from '@squidcloud/backend';
import { WebhookRequest } from '@squidcloud/client';

export class ExampleService extends SquidService {
@secureAiAgent()
allowChat(): boolean {
return true;
}

@webhook('askQuestion')
async askQuestion(request: WebhookRequest): Promise<string> {
if (!request.body?.question) throw new Error('MISSING_QUESTION');

const p: Promise<string> = new Promise((resolve, reject) => {
let res = '';
this.squid
.ai()
.agent('AGENT_ID') // Name of the profile you created earlier in that same integration
.chat(request.body.question)
.subscribe({
next: (answer) => {
res = answer;
},
error: () => reject('INTERNAL_ERROR'),
complete: () => {
resolve(res);
},
});
});
return await p;
}
}

Webhook decorator の SDK リファレンスドキュメントの全文は、こちらをクリックしてください。