Azure Web PubSub 채팅 클라이언트 라이브러리는 서버 애플리케이션이 Azure Web PubSub 채팅 허브 내에서 채팅 역할, 사용자, 방, 룸 멤버십, 대화, 메시지를 관리할 수 있도록 합니다.
시작하기
현재 지원되는 환경
자세한 내용은 지원 정책 참조하세요.
사전 요구 사항
- Azure 구독.
- 기존 Azure Web PubSub 리소스.
- 채팅 애플리케이션의 허브 이름입니다.
@azure/web-pubsub-chat 패키지 설치
JavaScript용 Azure WebPubSubChatService 클라이언트 라이브러리를 설치하세요npm:
npm install @azure/web-pubsub-chat
WebPubSubChatServiceClient를 만들고 인증하기
WebPubSubChatServiceClient 연결 문자열, Microsoft Entra 자격 증명 또는 AzureKeyCredential.을 통한 인증을 지원합니다.
연결 문자열으로 인증하세요
Azure Web PubSub 리소스의 연결 문자열은 Azure Portal에서 찾을 수 있습니다. 연결 문자열에 접근 키가 포함되어 있으므로, 안전하게 저장하고 소스 코드에는 포함하지 마세요.
Microsoft Entra ID로 인증
Microsoft Entra ID로 인증하려면 Azure Web PubSub 리소스와 자격 증명이 필요합니다endpoint. 엔드포인트는 Azure Portal에서 찾을 수 있습니다.
Microsoft Entra ID로 @azure/identity 라이브러리의 자격 증명이나 기존 Microsoft Entra 토큰을 사용해 인증할 수 있습니다.
아래에 표시된 DefaultAzureCredential 공급자 또는 Azure SDK와 함께 제공되는 다른 자격 증명 공급자를 사용하려면 @azure/identity 패키지를 설치하세요.
npm install @azure/identity
DefaultAzureCredential여러 Microsoft Entra 아이덴티티를 지원합니다. 로컬 개발 중에는 지원되는 개발 도구를 통해 로그인한 개발자 신원을 사용할 수 있습니다. Azure에서는 관리 신원을 사용할 수 있습니다. 환경에 맞게 설정되면 서비스 주체나 워크로드 신원을 인증할 수도 있습니다.
어떤 신원을 사용하든 적절한 Azure Web PubSub 데이터플레인 역할이 할당되어야 합니다. Azure resource-management roles such do not Owner 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>",
);
주요 개념
WebPubSubChatServiceClient
WebPubSubChatServiceClient 웹 퍼브서브 허브에서 채팅 자원을 관리하는 주요 인터페이스입니다.
허브
허브는 채팅 애플리케이션의 논리적 경계입니다. 클라이언트가 관리하는 역할, 사용자, 방, 대화, 메시지 모두 클라이언트 생성자에게 제공되는 허브에 속합니다.
역할 및 권한
사용자 역할은 방 생성과 같은 허브 수준의 작업을 제어합니다. 룸 역할은 메시지 게시, 메시지 기록 읽기, 사용자 초대 등 방 내 행동을 제어합니다.
방, 회원, 그리고 대화
방에는 멤버가 있고 기본 대화가 있습니다. 사용자에게 룸 역할을 할당하여 사용자를 룸에 추가하세요. 메시지는 연결된 채팅 클라이언트에서 게시되며, 서비스 클라이언트를 통해 목록, 업데이트 또는 삭제가 가능합니다.
엔터티 태그
채팅 자원에는 가치가 있습니다 etag . 그 값을 조건부 업데이트나 삭제를 수행하는 연산의 ifMatch 옵션을 통해 전달하여 최신 리소스 버전을 덮어쓰지 않도록 합니다.
예시
역할, 사용자, 그리고 방을 설정하세요
사용자 역할과 룸 역할을 만들고, 인간 사용자와 룸을 만든 후 사용자를 룸에 추가하세요.
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);
사용자 관리
내장 역할을 가진 사용자를 생성하고, 프로필을 불러와서 삭제하세요.
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);
대화 내 메시지를 나열하세요
비동기식 반복을 사용해 모든 결과 페이지에서 대화 메시지를 읽으세요.
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}`);
}
클라이언트 액세스 토큰 생성
채팅 클라이언트가 특정 사용자로서 웹 PubSub 서비스에 연결할 수 있는 URL을 생성하세요.
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" });
Troubleshooting
로깅 (로그 기록)
로깅을 사용하도록 설정하면 오류에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info설정합니다. 또는 setLogLevel@azure/logger 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
로그를 사용하도록 설정하는 방법에 대한 자세한 지침은 @azure/로거 패키지 문서를 참조하세요.
Contributing
이 라이브러리에 기여하려면 기여 가이드 읽어 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.
Azure SDK for JavaScript