ウェブフック
Webhook は、1 つの Web アプリケーションが別の Web アプリケーションと通信することを可能にするイベント駆動型アーキテクチャの一種です。
Webhook は、データベースでの新規レコードの作成、バグトラッカーでの問題のステータス変更、またはチャットアプリケーションでの新規メッセージなどのイベントによって起動される、ユーザー定義の HTTP コールバックとして機能します。
イベントが発生すると、ソースシステムは Webhook によって指定された URL に対して HTTP リクエストを送信し、それが Webhook と関連するコードの実行を引き起こします。HTTP リクエストのペイロードには通常、イベントに関連するデータが含まれており、受信側システムはそれを用いて追加の処理を行うことができます。
また、Webhook によって定義された URL にアクセスすることで、Webhook を呼び出すこともできます。Squid では、Webhook を公開して他の内部および外部サービスで利用できるようにする機能が備わっています。
Webhook の作成
Webhook を定義するには、SquidService
クラスを拡張したクラス内の関数に @webhook
デコレーターを適用するだけです:
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
リクエストオブジェクトは、クエリパラメータ、ボディ、ヘッダーなど、完全な HTTP コンテキストを提供します。
以下の例では、Squid のバックエンド SDK を使用して Squid AI Agent を API に変換し、Squid Client SDK の使用を置き換えています。
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 デコレーターの SDK リファレンスドキュメントの全文を確認するには、こちら をクリックしてください。