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

Webhooks

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

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

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

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

Creating a 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でアクセスできます:

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

リクエストオブジェクトは、クエリパラメーター、ボディ、ヘッダーなど、完全なHTTPコンテキストを提供します.

以下のサンプルコードは、Squidのbackend SDKを使用して Squid AI Agent をAPIに変換する例です。これにより、Squid Client SDKの使用が不要になります.

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

export class ExampleService extends SquidService {
@secureAiAgent('chat')
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リファレンスドキュメントを見るには、こちらをクリックしてください.