你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

Azure Web PubSub JavaScript 聊天客户端库 - 版本 1.0.0-beta.2

Azure Web PubSub 聊天客户端库使服务器应用程序能够在 Azure Web PubSub 聊天中心管理聊天角色、用户、聊天室、主题、聊天室成员资格、会话和消息。 使用它来将讨论组织成房间主题,发现用户及其房间,并从服务器应用程序管理聊天资源。

关键链接:

入门

目前支持的环境

有关更多详细信息,请参阅我们的支持政策。

先决条件

  • Azure 订阅。
  • 一个现有的 Azure Web PubSub 资源。
  • 一个配置了启用聊天功能并具备持久存储功能的集线器。

安装 @azure/web-pubsub-chat 包

安装 Azure WebPubSubChatService JavaScript 客户端库,使用:npm

npm install @azure/web-pubsub-chat

配置 TypeScript

此软件包包含 TypeScript 声明。 对于用 TypeScript 编写的 Node.js 应用程序,安装 Node.js 类型定义:

npm install --save-dev @types/node

无需额外的针对软件包的编译器设置。

创建和验证 WebPubSubChatServiceClient

它WebPubSubChatServiceClient支持通过连接字符串、Microsoft Entra凭证AzureKeyCredential或.进行认证。

用连接字符串认证

你可以在Azure 门户中找到Azure Web PubSub资源的连接字符串。 由于 连接字符串 包含访问密钥,请安全存储,且不包含在源代码中。

使用 Microsoft Entra ID 进行身份验证

要用 Microsoft Entra ID 认证,你需要endpoint你的 Azure Web PubSub 资源和凭证。 你可以在 Azure 门户 中找到该端点。

你可以用@azure/identity库中的凭据或现有的Microsoft Entra令牌进行Microsoft Entra ID认证。

若要使用如下所示的 DefaultAzureCredential 提供程序,或 Azure SDK 提供的其他凭据提供程序,请安装 @azure/identity 包:

npm install @azure/identity

DefaultAzureCredential支持多个 Microsoft Entra 身份。 在本地开发过程中,它可以使用通过支持的开发工具登录的开发者身份。 在 Azure 中,它可以使用托管身份。 在配置时,它还能认证服务主体或工作负载身份。

无论你使用哪种身份,都必须被分配一个合适的 Azure Web PubSub 数据平面角色。 Azure resource-management roles like do Owner not grant data-plane permissions.

创建客户端时,可以使用连接字符串、Microsoft Entra凭证(如DefaultAzureCredential,或)AzureKeyCredential创建。

import { WebPubSubChatServiceClient, AzureKeyCredential } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const connectionStringClient = new WebPubSubChatServiceClient("<connectionString>", "<hubName>");
const tokenCredentialClient = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const keyCredentialClient = new WebPubSubChatServiceClient(
  "<endpoint>",
  new AzureKeyCredential("<accessKey>"),
  "<hubName>",
);

重要概念

Hub

集线器是 WebSocket 连接的逻辑集合。 聊天中心增加了内置聊天室、成员管理、消息持久化以及针对聊天的 API。

此 SDK 仅适用于聊天中心。 必须在目标中心启用聊天功能,SDK 才能管理角色、用户、房间、成员、会话或消息。

角色与权限

角色是一组命名的聊天权限集合。 用户角色名称以 user.开头,房间角色名称以 room.开头。 不要将用户权限和房间权限合并到一个角色中。

用户角色控制诸如创建房间等操作。 房间角色控制成员在特定房间中可以做的事情,比如发布消息或阅读消息历史。

用户

用户代表参与聊天的身份,例如人类终端用户或应用程序。 客户端访问凭据将 WebSocket 连接与用户 ID 关联。

房间

一个房间将用户分组在一起,是聊天互动的主要组织单元。 每个房间都有自动创建的默认对话。

房间成员

房间成员代表添加到房间中的用户。 成员资格控制哪些用户可以在房间内接收和发送消息。 在服务 API 中,每个房间成员被分配了一个房间角色。

对话与消息历史

对话是房间内有序的消息流。 每个房间都有默认对话,并且可以通过主题创建额外的命名对话。

发送到对话中的消息会实时发送给房间中已连接的成员。 聊天服务负责管理排序和持久化,允许成员在重新连接或稍后加入后加载消息历史。 服务客户端可以列出、更新和删除持久化的消息。

Topic

一个主题表示房间内的一个命名对话。 主题可以独立于房间的默认对话内容进行创建、重命名、归档和软删除。

Examples

设置角色、用户和房间

创建用户和房间角色,创建一个人类用户和一个房间,然后将用户添加到房间。

import { WebPubSubChatServiceClient, KnownChatPermission } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const userRoleName = "user.contoso_member";
const roomRoleName = "room.contoso_member";
const userId = "alice";
const roomId = "general";
await client.createOrReplaceRole(userRoleName, {
  permissions: [KnownChatPermission.UserCreateRoom],
});
await client.createOrReplaceRole(roomRoleName, {
  permissions: [KnownChatPermission.RoomPublishMessage, KnownChatPermission.RoomHistory],
});
await client.createOrReplaceUser(userId, {
  kind: "Human",
  nickname: "Alice",
  roleName: userRoleName,
});
const room = await client.createOrReplaceRoom(roomId, { title: "General" });
await client.createOrReplaceRoomMember(roomId, userId, { roleName: roomRoleName });
console.log(`Created room ${room.id} with conversation ${room.defaultConversation}`);

使用内置角色和已知权限

在分配服务定义角色和KnownChatPermission创建自定义角色时使用BuiltInChatRoles。 已知值之外的权限字符串也被接受以实现前向兼容性。

import {
  WebPubSubChatServiceClient,
  BuiltInChatRoles,
  KnownChatPermission,
} from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
await client.createOrReplaceUser("alice", {
  kind: "Human",
  nickname: "Alice",
  roleName: BuiltInChatRoles.UserNormal,
});
await client.createOrReplaceRole("room.moderator", {
  permissions: [
    KnownChatPermission.RoomHistory,
    KnownChatPermission.RoomRemoveUser,
    KnownChatPermission.RoomPublishMessage,
  ],
});

管理角色

创建一个自定义角色,取回它,在中心中列出角色,完成后删除自定义角色。

import { WebPubSubChatServiceClient, KnownChatPermission } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const roleName = "user.contoso_member";
try {
  const role = await client.createOrReplaceRole(roleName, {
    permissions: [KnownChatPermission.UserCreateRoom, KnownChatPermission.UserFetchAllRooms],
  });
  console.log(`Created role: ${role.name}`);
  const fetchedRole = await client.getRole(roleName);
  console.log(`Fetched role: ${fetchedRole.name}`);
  for await (const listedRole of client.listRoles()) {
    console.log(`Role: ${listedRole.name}`);
  }
} finally {
  await client.deleteRole(roleName);
}

管理一个房间

创建一个房间,获取当前状态并删除它。

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const roomId = "general";
const room = await client.createOrReplaceRoom(roomId, { title: "General" });
console.log(`Created room ${room.id} with conversation ${room.defaultConversation}`);
const fetchedRoom = await client.getRoom(roomId);
console.log(`Fetched room: ${fetchedRoom.id}, title: ${fetchedRoom.title}`);
await client.deleteRoom(roomId);

管理用户

创建一个内置角色的用户,取回配置文件,然后删除它。 请求接受 HumanChatUserCreateOrReplace,这需要 kind: "Human"、 nickname和 roleName。 返回的配置文件保留资源字段,并可能表示未知的用户类型。

import { WebPubSubChatServiceClient, BuiltInChatRoles } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const userId = "alice";
const user = await client.createOrReplaceUser(userId, {
  kind: "Human",
  nickname: "Alice",
  roleName: BuiltInChatRoles.UserNormal,
});
console.log(`Created user: ${user.id}, nickname: ${user.nickname}`);
const fetchedUser = await client.getUser(userId);
console.log(`Fetched user: ${fetchedUser.id}, nickname: ${fetchedUser.nickname}`);
await client.deleteUser(userId);

更新一条消息

在更新消息时, ChatMessageUpdate.createdBy 和 content 都是可选的。 只提供需要更改的字段;省略的字段保留其当前值。

在对话中列出消息

使用异步迭代,从最新到最早读取所有结果页对话中的消息。 消息 ID 是分页光标:迭代器跟随服务的 nextLink,后者包含下一个消息 ID 光标。 若要稍后继续,保存页面并 continuationToken 传递给 byPage({ continuationToken });使用返回的令牌不更改,而非传入纯消息 ID。

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
for await (const message of client.listMessages("<conversationId>")) {
  console.log(`${message.createdBy}: ${message.content.text}`);
}

生成客户端访问令牌

生成一个URL,供聊天客户端作为特定用户连接到Web PubSub服务。

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const accessToken = await client.getClientAccessToken({ userId: "alice" });

在中心中列出房间

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
for await (const room of client.listRooms({ maxPageSize: 20 })) {
  console.log(`${room.id}: ${room.title}`);
}

在中心中列出用户

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
for await (const user of client.listUsers({ maxPageSize: 20 })) {
  console.log(`${user.id}: ${user.nickname}`);
}

列出用户的房间

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
for await (const room of client.listRoomsForUser("alice", { maxPageSize: 20 })) {
  console.log(`${room.id}: ${room.title}`);
}

创建主题

在现有房间中创建一个主题。 该服务创建其关联的对话。

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const topic = await client.createOrReplaceTopic(
  "general",
  "announcements",
  {
    title: "Announcements",
  },
  { ifNoneMatch: "*" },
);
console.log(`Topic conversation: ${topic.conversationId}`);

获取主题

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const topic = await client.getTopic("general", "announcements");
console.log(`${topic.title}: ${topic.state}, ETag: ${topic.etag}`);

更新主题

存档现有主题而不更改其标题。 将其替换 <etag> 为当前实体标签。

import { WebPubSubChatServiceClient, KnownChatTopicState } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const topic = await client.updateTopic(
  "general",
  "announcements",
  {
    state: KnownChatTopicState.Archived,
  },
  { ifMatch: "<etag>" },
);
console.log(`Topic state: ${topic.state}`);

在房间中列出主题

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
for await (const topic of client.listTopics("general", { maxPageSize: 20 })) {
  console.log(`${topic.id}: ${topic.title} (${topic.state})`);
}

简历主题分页

列表操作接受通过 byPage({ continuationToken })的延续令牌,而非通过列表方法的选项。 将返回的令牌传递在页面上不作更改。

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
const pages = client.listTopics("general", { maxPageSize: 20 }).byPage();
const firstPage = await pages.next();
if (!firstPage.done) {
  console.log(firstPage.value);
  const continuationToken = firstPage.value.continuationToken;
  if (continuationToken) {
    const resumedPages = client
      .listTopics("general", { maxPageSize: 20 })
      .byPage({ continuationToken });
    const nextPage = await resumedPages.next();
    console.log(nextPage.value);
  }
}

删除主题

软删除现有主题。 将其替换 <etag> 为当前实体标签。

import { WebPubSubChatServiceClient } from "@azure/web-pubsub-chat";
import { DefaultAzureCredential } from "@azure/identity";

const client = new WebPubSubChatServiceClient(
  "<endpoint>",
  new DefaultAzureCredential(),
  "<hubName>",
);
await client.deleteTopic("general", "announcements", { ifMatch: "<etag>" });

Troubleshooting

服务错误和条件请求

服务失败抛出时会抛出 RestErrorstatusCode. HTTP 404 表示缺失的资源,包括已删除的主题。 HTTP 412 表示某个ifMatchifNoneMatch前提条件失败。 在重试条件写入之前,先获取当前资源并检查其实体标签。 仅在资源尚未存在时创建该资源时使用 ifNoneMatch: "*" 。

伐木业

启用日志记录可能有助于发现有关故障的有用信息。 若要查看 HTTP 请求和响应的日志,请将 AZURE_LOG_LEVEL 环境变量设置为 info。 或者,可以通过在 setLogLevel中调用 @azure/logger 在运行时启用日志记录:

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

有关如何启用日志的更详细说明,可以查看 @azure/记录器包文档。

后续步骤

探索 JavaScript 和 TypeScript 示例 以及 API 引用。

Contributing

若要参与此库,请阅读 贡献指南 了解有关如何生成和测试代码的详细信息。