opção
LarLar Skill Desenvolvimento de APIs azure-web-pubsub-ts

azure-web-pubsub-ts

microsoft/skills microsoft/skills

Construa aplicativos de mensagens em tempo real usando os SDKs do Azure Web PubSub para JavaScript, incluindo gerenciamento do lado do servidor, publicação/assinatura do lado do cliente e manipuladores de eventos do Express.

...Expandir tudo
0
Tempo atualizado 13 de Setembro de 2026

SDKs do Azure Web PubSub para TypeScript

Mensagens em tempo real com conexões WebSocket e padrões de publicação/assinatura.

Instalação

# Gerenciamento do lado do servidor
npm install @azure/web-pubsub @azure/identity

# Mensagens em tempo real do lado do cliente
npm install @azure/web-pubsub-client

# Middleware do Express para manipuladores de eventos
npm install @azure/web-pubsub-express

Variáveis de Ambiente

WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<recurso>.webpubsub.azure.com;AccessKey=<chave>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<recurso>.webpubsub.azure.com
AZURE_TOKEN_CREDENTIALS=prod # Necessário apenas se DefaultAzureCredential for usado em produção
</recurso></chave></recurso>

Lado do Servidor: WebPubSubServiceClient

Autenticação

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

// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credencial_específica>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Ou use uma credencial específica diretamente em produção:
// Consulte https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

// String de conexão
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // nome do hub
);

// Credencial de Token do Microsoft Entra (recomendado)
const client2 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  credential,
  "chat"
);

// AzureKeyCredential
const client3 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new AzureKeyCredential("<chave-de-acesso>"),
  "chat"
);
</chave-de-acesso></credencial_específica>

Gerar Token de Acesso do Cliente

// Token básico
const token = await client.getClientAccessToken();
console.log(token.url);  // wss://...?access_token=...

// Token com ID de usuário
const userToken = await client.getClientAccessToken({
  userId: "user123",
});

// Token com permissões
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup",
    "webpubsub.sendToGroup",
    "webpubsub.sendToGroup.chat-room",  // grupo específico
  ],
  groups: ["chat-room"],  // entrar automaticamente ao conectar
  expirationTimeInMinutes: 60,
});

Enviar Mensagens

// Transmissão para todas as conexões no hub
await client.sendToAll({ message: "Olá a todos!" });
await client.sendToAll("Texto simples", { contentType: "text/plain" });

// Enviar para um usuário específico (todas as suas conexões)
await client.sendToUser("user123", { message: "Olá!" });

// Enviar para uma conexão específica
await client.sendToConnection("connectionId", { data: "Mensagem direta" });

// Enviar com filtro (sintaxe OData)
await client.sendToAll({ message: "Filtrado" }, {
  filter: "userId ne 'admin'",
});

Gerenciamento de Grupos

const group = client.group("chat-room");

// Adicionar usuário/conexão ao grupo
await group.addUser("user123");
await group.addConnection("connectionId");

// Remover do grupo
await group.removeUser("user123");

// Enviar para o grupo
await group.sendToAll({ message: "Mensagem do grupo" });

// Fechar todas as conexões no grupo
await group.closeAllConnections({ reason: "Manutenção" });

Gerenciamento de Conexões

// Verificar existência
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// Fechar conexões
await client.closeConnection("connectionId", { reason: "Expulso" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

// Permissões
await client.grantPermission("connectionId", "sendToGroup", { targetName: "chat" });
await client.revokePermission("connectionId", "sendToGroup", { targetName: "chat" });

Lado do Cliente: WebPubSubClient

Conectar

import { WebPubSubClient } from "@azure/web-pubsub-client";

// URL direta
const client = new WebPubSubClient("<url-de-acesso-do-cliente>");

// URL dinâmica do ponto de extremidade de negociação
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// Registrar manipuladores ANTES de iniciar
client.on("connected", (e) => {
  console.log(`Conectado: ${e.connectionId}`);
});

client.on("group-message", (e) => {
  console.log(`${e.message.group}: ${e.message.data}`);
});

await client.start();
</url-de-acesso-do-cliente>

Enviar Mensagens

// Entrar no grupo primeiro
await client.joinGroup("chat-room");

// Enviar para o grupo
await client.sendToGroup("chat-room", "Olá!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Oi" }, "json");

// Opções de envio
await client.sendToGroup("chat-room", "Olá", "text", {
  noEcho: true,        // Não ecoar de volta para o remetente
  fireAndForget: true, // Não aguardar confirmação
});

// Enviar evento para o servidor
await client.sendEvent("userAction", { action: "digitando" }, "json");

Manipuladores de Eventos

// Ciclo de vida da conexão
client.on("connected", (e) => {
  console.log(`Conectado: ${e.connectionId}, Usuário: ${e.userId}`);
});

client.on("disconnected", (e) => {
  console.log(`Desconectado: ${e.message}`);
});

client.on("stopped", () => {
  console.log("Cliente parado");
});

// Mensagens
client.on("group-message", (e) => {
  console.log(`[${e.message.group}] ${e.message.fromUserId}: ${e.message.data}`);
});

client.on("server-message", (e) => {
  console.log(`Servidor: ${e.message.data}`);
});

// Falha ao reconectar-se
client.on("rejoin-group-failed", (e) => {
  console.log(`Falha ao reconectar-se a ${e.group}: ${e.error}`);
});

Manipulador de Eventos do Express

import express from "express";
import { WebPubSubEventHandler } from "@azure/web-pubsub-express";

const app = express();

const handler = new WebPubSubEventHandler("chat", {
  path: "/api/webpubsub/hubs/chat/",

  // Bloqueante: aprovar/rejeitar conexão
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "Autenticação necessária");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["geral"],
      roles: ["webpubsub.sendToGroup"],
    });
  },

  // Bloqueante: lidar com eventos personalizados
  handleUserEvent: (req, res) => {
    console.log(`Evento de ${req.context.userId}:`, req.data);
    res.success(`Recebido: ${req.data}`, "text");
  },

  // Não bloqueante
  onConnected: (req) => {
    console.log(`Cliente conectado: ${req.context.connectionId}`);
  },

  onDisconnected: (req) => {
    console.log(`Cliente desconectado: ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// Ponto de extremidade de negociação
app.get("/negotiate", async (req, res) => {
  const token = await serviceClient.getClientAccessToken({
    userId: req.user?.id,
  });
  res.json({ url: token.url });
});

app.listen(8080);

Tipos Principais

// Servidor
import {
  WebPubSubServiceClient,
  WebPubSubGroup,
  GenerateClientTokenOptions,
  HubSendToAllOptions,
} from "@azure/web-pubsub";

// Cliente
import {
  WebPubSubClient,
  WebPubSubClientOptions,
  OnConnectedArgs,
  OnGroupDataMessageArgs,
} from "@azure/web-pubsub-client";

// Express
import {
  WebPubSubEventHandler,
  ConnectRequest,
  UserEventRequest,
  ConnectResponseHandler,
} from "@azure/web-pubsub-express";

Melhores Práticas

  1. Usar Credencial de Token do Microsoft Entra - Use DefaultAzureCredential para desenvolvimento local; use ManagedIdentityCredential ou WorkloadIdentityCredential para produção
  2. Registrar manipuladores antes de iniciar - Não perca eventos iniciais
  3. Usar grupos para canais - Organize mensagens por tópico/sala
  4. Tratar reconexão - O cliente se reconecta automaticamente por padrão
  5. Validar em handleConnect - Rejeite conexões não autorizadas antecipadamente
  6. Usar noEcho - Evite o eco da mensagem de volta para o remetente quando necessário
Ver no GitHub
---
name: azure-web-pubsub-ts
description: Build real-time messaging applications using Azure Web PubSub SDKs for JavaScript, including server-side management, client-side pub/sub, and Express event handlers.
license: MIT
---

# Azure Web PubSub SDKs for TypeScript

Real-time messaging with WebSocket connections and pub/sub patterns.

## Installation

```bash
# Server-side management
npm install @azure/web-pubsub @azure/identity

# Client-side real-time messaging
npm install @azure/web-pubsub-client

# Express middleware for event handlers
npm install @azure/web-pubsub-express
```

## Environment Variables

```bash
WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=<key>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Server-Side: WebPubSubServiceClient

### Authentication

```typescript
import { WebPubSubServiceClient, AzureKeyCredential } from "@azure/web-pubsub";
import { DefaultAzureCredential, ManagedIdentityCredential } from "@azure/identity";

// Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
const credential = new DefaultAzureCredential({requiredEnvVars: ["AZURE_TOKEN_CREDENTIALS"]});
// Or use a specific credential directly in production:
// See https://learn.microsoft.com/javascript/api/overview/azure/identity-readme?view=azure-node-latest#credential-classes
// const credential = new ManagedIdentityCredential();

// Connection string
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // hub name
);

// Microsoft Entra Token Credential (recommended)
const client2 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  credential,
  "chat"
);

// AzureKeyCredential
const client3 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new AzureKeyCredential("<access-key>"),
  "chat"
);
```

### Generate Client Access Token

```typescript
// Basic token
const token = await client.getClientAccessToken();
console.log(token.url);  // wss://...?access_token=...

// Token with user ID
const userToken = await client.getClientAccessToken({
  userId: "user123",
});

// Token with permissions
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup",
    "webpubsub.sendToGroup",
    "webpubsub.sendToGroup.chat-room",  // specific group
  ],
  groups: ["chat-room"],  // auto-join on connect
  expirationTimeInMinutes: 60,
});
```

### Send Messages

```typescript
// Broadcast to all connections in hub
await client.sendToAll({ message: "Hello everyone!" });
await client.sendToAll("Plain text", { contentType: "text/plain" });

// Send to specific user (all their connections)
await client.sendToUser("user123", { message: "Hello!" });

// Send to specific connection
await client.sendToConnection("connectionId", { data: "Direct message" });

// Send with filter (OData syntax)
await client.sendToAll({ message: "Filtered" }, {
  filter: "userId ne 'admin'",
});
```

### Group Management

```typescript
const group = client.group("chat-room");

// Add user/connection to group
await group.addUser("user123");
await group.addConnection("connectionId");

// Remove from group
await group.removeUser("user123");

// Send to group
await group.sendToAll({ message: "Group message" });

// Close all connections in group
await group.closeAllConnections({ reason: "Maintenance" });
```

### Connection Management

```typescript
// Check existence
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// Close connections
await client.closeConnection("connectionId", { reason: "Kicked" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

// Permissions
await client.grantPermission("connectionId", "sendToGroup", { targetName: "chat" });
await client.revokePermission("connectionId", "sendToGroup", { targetName: "chat" });
```

## Client-Side: WebPubSubClient

### Connect

```typescript
import { WebPubSubClient } from "@azure/web-pubsub-client";

// Direct URL
const client = new WebPubSubClient("<client-access-url>");

// Dynamic URL from negotiate endpoint
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// Register handlers BEFORE starting
client.on("connected", (e) => {
  console.log(`Connected: ${e.connectionId}`);
});

client.on("group-message", (e) => {
  console.log(`${e.message.group}: ${e.message.data}`);
});

await client.start();
```

### Send Messages

```typescript
// Join group first
await client.joinGroup("chat-room");

// Send to group
await client.sendToGroup("chat-room", "Hello!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Hi" }, "json");

// Send options
await client.sendToGroup("chat-room", "Hello", "text", {
  noEcho: true,        // Don't echo back to sender
  fireAndForget: true, // Don't wait for ack
});

// Send event to server
await client.sendEvent("userAction", { action: "typing" }, "json");
```

### Event Handlers

```typescript
// Connection lifecycle
client.on("connected", (e) => {
  console.log(`Connected: ${e.connectionId}, User: ${e.userId}`);
});

client.on("disconnected", (e) => {
  console.log(`Disconnected: ${e.message}`);
});

client.on("stopped", () => {
  console.log("Client stopped");
});

// Messages
client.on("group-message", (e) => {
  console.log(`[${e.message.group}] ${e.message.fromUserId}: ${e.message.data}`);
});

client.on("server-message", (e) => {
  console.log(`Server: ${e.message.data}`);
});

// Rejoin failure
client.on("rejoin-group-failed", (e) => {
  console.log(`Failed to rejoin ${e.group}: ${e.error}`);
});
```

## Express Event Handler

```typescript
import express from "express";
import { WebPubSubEventHandler } from "@azure/web-pubsub-express";

const app = express();

const handler = new WebPubSubEventHandler("chat", {
  path: "/api/webpubsub/hubs/chat/",
  
  // Blocking: approve/reject connection
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "Authentication required");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["general"],
      roles: ["webpubsub.sendToGroup"],
    });
  },
  
  // Blocking: handle custom events
  handleUserEvent: (req, res) => {
    console.log(`Event from ${req.context.userId}:`, req.data);
    res.success(`Received: ${req.data}`, "text");
  },
  
  // Non-blocking
  onConnected: (req) => {
    console.log(`Client connected: ${req.context.connectionId}`);
  },
  
  onDisconnected: (req) => {
    console.log(`Client disconnected: ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// Negotiate endpoint
app.get("/negotiate", async (req, res) => {
  const token = await serviceClient.getClientAccessToken({
    userId: req.user?.id,
  });
  res.json({ url: token.url });
});

app.listen(8080);
```

## Key Types

```typescript
// Server
import {
  WebPubSubServiceClient,
  WebPubSubGroup,
  GenerateClientTokenOptions,
  HubSendToAllOptions,
} from "@azure/web-pubsub";

// Client
import {
  WebPubSubClient,
  WebPubSubClientOptions,
  OnConnectedArgs,
  OnGroupDataMessageArgs,
} from "@azure/web-pubsub-client";

// Express
import {
  WebPubSubEventHandler,
  ConnectRequest,
  UserEventRequest,
  ConnectResponseHandler,
} from "@azure/web-pubsub-express";
```

## Best Practices

1. **Use Microsoft Entra Token Credential** - Use `DefaultAzureCredential` for local development; use `ManagedIdentityCredential` or `WorkloadIdentityCredential` for production
2. **Register handlers before start** - Don't miss initial events
3. **Use groups for channels** - Organize messages by topic/room
4. **Handle reconnection** - Client auto-reconnects by default
5. **Validate in handleConnect** - Reject unauthorized connections early
6. **Use noEcho** - Prevent message echo back to sender when needed

Todos os arquivos

0 arquivos

Instalar azure-web-pubsub-ts

Baixe e extraia os arquivos de habilidade para o diretório .claude/skills/.

Baixar ZIP

Clone o repositório e copie os arquivos da habilidade para o seu projeto.

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-typescript/skills/azure-web-pubsub-ts # Copy SKILL.md to your .claude/skills/ directory

Copiar Copiar
Configuração rápida: Copie a pasta de habilidades para .claude/skills/ O Claude detectará e usará automaticamente a habilidade
Repositório microsoft/skills

Habilidades relacionadas

brightdata-cli
Tempo atualizado 29 de Junho de 2026
humanize
Tempo atualizado 7 de Julho de 2026
agentwallet
Tempo atualizado 7 de Julho de 2026
korean-stock-search
Tempo atualizado 8 de Julho de 2026
OR