WebSocket 链接
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
wsLink 是一种终止链接,用于实现 tRPC 的 WebSockets 客户端和订阅功能,更多详细信息可参阅此处。
用法
使用 wsLink 时,需要向其传递 TRPCWebSocketClient 实例,该实例可通过 createWSClient 创建:
client/index.tstsimport { createTRPCProxyClient, createWSClient, wsLink } from '@trpc/client';import type { AppRouter } from '../server';const wsClient = createWSClient({url: 'ws://localhost:3000',});const trpcClient = createTRPCProxyClient<AppRouter>({links: [wsLink<AppRouter>({ client: wsClient })],});
client/index.tstsimport { createTRPCProxyClient, createWSClient, wsLink } from '@trpc/client';import type { AppRouter } from '../server';const wsClient = createWSClient({url: 'ws://localhost:3000',});const trpcClient = createTRPCProxyClient<AppRouter>({links: [wsLink<AppRouter>({ client: wsClient })],});
wsLink 选项
wsLink 函数需要接收一个 TRPCWebSocketClient 参数,该参数可通过 WebSocketClientOptions 中定义的字段进行配置:
tsexport interface WebSocketLinkOptions {client: TRPCWebSocketClient;}function createWSClient(opts: WebSocketClientOptions) => TRPCWebSocketClientexport interface WebSocketClientOptions {url: string;WebSocket?: typeof WebSocket;retryDelayMs?: typeof retryDelay;onOpen?: () => void;onClose?: (cause?: { code?: number }) => void;}
tsexport interface WebSocketLinkOptions {client: TRPCWebSocketClient;}function createWSClient(opts: WebSocketClientOptions) => TRPCWebSocketClientexport interface WebSocketClientOptions {url: string;WebSocket?: typeof WebSocket;retryDelayMs?: typeof retryDelay;onOpen?: () => void;onClose?: (cause?: { code?: number }) => void;}
参考文档
你可以在 GitHub 上查看此链接的源代码。