リファレンス - Azure Web PubSub 用の JavaScript SDK

Azure Web PubSub サービスは、開発者がリアルタイムの機能と発行-サブスクライブ パターンを利用して Web アプリケーションを簡単に作成できるようにするための Azure マネージド サービスです。 サーバーとクライアント間、またはクライアント間で、リアルタイムのパブリッシュ-サブスクライブ メッセージングを必要とするあらゆるシナリオに、Azure Web PubSub サービスを使用できます。 従来のリアルタイム機能は、多くの場合、サーバーからのポーリングや HTTP 要求の送信を必要としますが、そのようなリアルタイム機能にも Azure Web PubSub サービスを使用できます。

JavaScript には、サービス クライアント ライブラリと Express ミドルウェアの 2 つのライブラリが用意されています。 以下のセクションでは、これらのライブラリの詳細について説明します。

JavaScript 用 Azure Web PubSub サービス クライアント ライブラリ

次の図に示すように、このライブラリをアプリ サーバー側で使用して、WebSocket クライアント接続を管理できます。

The overflow diagram shows the overflow of using the service client library.

  • ハブとグループにメッセージを送信します。
  • 特定のユーザーと接続にメッセージを送信します。
  • ユーザーと接続をグループに整理します。
  • 接続を終了します
  • 既存の接続のアクセス許可を付与、取り消し、確認します

ソース コード | パッケージ (NPM) | API リファレンス ドキュメント | 製品ドキュメント | サンプル

作業の開始

現在サポートされている環境

前提条件

1. @azure/web-pubsub パッケージをインストールする

npm install @azure/web-pubsub

2. WebPubSubServiceClient を作成して認証する

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

エンドポイントと AzureKeyCredential を使用して WebPubSubServiceClient を認証できます。

const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

const key = new AzureKeyCredential("<Key>");
const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  key,
  "<hubName>"
);

または、Microsoft Entra ID を使用して WebPubSubServiceClient を認証します

  1. @azure/identity 依存関係をインストールします。
npm install @azure/identity
  1. DefaultAzureCredential を使用するようにソース コードを更新します。
const {
  WebPubSubServiceClient,
  AzureKeyCredential,
} = require("@azure/web-pubsub");

const key = new DefaultAzureCredential();
const serviceClient = new WebPubSubServiceClient(
  "<Endpoint>",
  key,
  "<hubName>"
);

クライアントが WebSocket 接続を開始するためのアクセス トークンを取得する

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

// Get the access token for the WebSocket client connection to use
let token = await serviceClient.getClientAccessToken();

// Or get the access token and assign the client a userId
token = await serviceClient.getClientAccessToken({ userId: "user1" });

// return the token to the WebSocket client

ハブ内のすべてのクライアント接続にメッセージをブロードキャストする

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

// Send a JSON message
await serviceClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToAll(payload.buffer);

グループ内のすべての接続にメッセージを送信する

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

const groupClient = serviceClient.group("<groupName>");

// Add user to the group
await groupClient.addUser("user1");

// Send a JSON message
await groupClient.sendToAll({ message: "Hello world!" });

// Send a plain text message
await groupClient.sendToAll("Hi there!", { contentType: "text/plain" });

// Send a binary message
const payload = new Uint8Array(10);
await groupClient.sendToAll(payload.buffer);

ユーザーのすべての接続にメッセージを送信する

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

// Send a JSON message
await serviceClient.sendToUser("user1", { message: "Hello world!" });

// Send a plain text message
await serviceClient.sendToUser("user1", "Hi there!", {
  contentType: "text/plain",
});

// Send a binary message
const payload = new Uint8Array(10);
await serviceClient.sendToUser("user1", payload.buffer);

グループに接続が存在するかどうかを確認する

const { WebPubSubServiceClient } = require("@azure/web-pubsub");
const WebSocket = require("ws");

const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);

const groupClient = serviceClient.group("<groupName>");

// close all the connections in the group
await groupClient.closeAllConnections({ reason: "<closeReason>" });

// check if the group has any connections
const hasConnections = await serviceClient.groupExists("<groupName>");

操作の生の HTTP 応答にアクセスする

const { WebPubSubServiceClient } = require("@azure/web-pubsub");

function onResponse(rawResponse: FullOperationResponse): void {
  console.log(rawResponse);
}
const serviceClient = new WebPubSubServiceClient(
  "<ConnectionString>",
  "<hubName>"
);
await serviceClient.sendToAll({ message: "Hello world!" }, { onResponse });

サービス クライアントのトラブルシューティング

ログの有効化

このライブラリの使用時にデバッグ ログを表示するには、次の環境変数を取得します。

  • Azure Web PubSub クライアント ライブラリからデバッグ ログを取得する
export AZURE_LOG_LEVEL=verbose

ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。

ライブ トレース

ライブトラフィックを表示するには、Web PubSub サービス ポータルから ライブ トレースを使用します。

Express 用 Azure Web Pubsub CloudEvents ハンドラー

WebSocket が接続すると、Web PubSub サービスが接続ライフサイクルとメッセージを CloudEvents 形式のイベントに変換します。 次の図に示したように、このライブラリは、WebSocket 接続のライフサイクルとメッセージを表すイベントを処理するための Express ミドルウェアを備えています。

The overflow diagram shows the overflow of using the event handler middleware.

ソース コード | パッケージ (NPM) | API リファレンス ドキュメント | 製品ドキュメント | サンプル

作業の開始

現在サポートされている環境

前提条件

1. @azure/web-pubsub-express パッケージをインストールする

npm install @azure/web-pubsub-express

2. WebPubSubEventHandler を作成する

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat");

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

簡易な例

connect 要求を処理して <userId> を割り当てる

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  handleConnect: (req, res) => {
    // auth the connection and set the userId of the connection
    res.success({
      userId: "<userId>",
    });
  },
  allowedEndpoints: ["https://<yourAllowedService>.webpubsub.azure.com"],
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

指定されたエンドポイントのみを許可する

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  allowedEndpoints: [
    "https://<yourAllowedService1>.webpubsub.azure.com",
    "https://<yourAllowedService2>.webpubsub.azure.com",
  ],
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

カスタム イベント ハンドラーのパスを設定する

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");
const handler = new WebPubSubEventHandler("chat", {
  path: "/customPath1",
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  // Azure WebPubSub Upstream ready at http://localhost:3000/customPath1
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

接続状態の設定と読み取りを行う

const express = require("express");

const { WebPubSubEventHandler } = require("@azure/web-pubsub-express");

const handler = new WebPubSubEventHandler("chat", {
  handleConnect(req, res) {
    // You can set the state for the connection, it lasts throughout the lifetime of the connection
    res.setState("calledTime", 1);
    res.success();
  },
  handleUserEvent(req, res) {
    var calledTime = req.context.states.calledTime++;
    console.log(calledTime);
    // You can also set the state here
    res.setState("calledTime", calledTime);
    res.success();
  },
});

const app = express();

app.use(handler.getMiddleware());

app.listen(3000, () =>
  console.log(
    `Azure WebPubSub Upstream ready at http://localhost:3000${handler.path}`
  )
);

トラブルシューティング

ログの有効化

このライブラリの使用時にデバッグ ログを表示するには、次の環境変数を取得します。

  • Azure Web PubSub クライアント ライブラリからデバッグ ログを取得する
export AZURE_LOG_LEVEL=verbose

ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。

ライブ トレース

ライブトラフィックを表示するには、Web PubSub サービス ポータルから ライブ トレースを使用します。

次のステップ

これらのリソースを使用して、独自のアプリケーションの構築を開始します。