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

ウェブフック

Webhookは、1つのWebアプリケーションが別のWebアプリケーションと通信することを可能にする、イベント駆動型アーキテクチャの一種です。

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

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

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

ウェブフックの作成

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

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オブジェクトは、クエリパラメータ、ボディ、ヘッダーなど、完全なHTTPコンテキストを提供します。

以下のサンプルコードでは、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デコレータの完全なSDKリファレンスドキュメントを確認するには、hereをクリックしてください.