サブスクリプション/WebSockets
サブスクリプションの使用
ヒント
- フルスタックの例については、/examples/next-prisma-starter-websocketsをご覧ください。
- 最小限のNode.jsの例については、/examples/standalone-serverを参照してください。
サブスクリプションプロシージャの追加
server/router.tstsx
import { EventEmitter } from 'events';import { initTRPC } from '@trpc/server';import { observable } from '@trpc/server/observable';import { z } from 'zod';// create a global event emitter (could be replaced by redis, etc)const ee = new EventEmitter();const t = initTRPC.create();export const appRouter = t.router({onAdd: t.procedure.subscription(() => {// return an `observable` with a callback which is triggered immediatelyreturn observable<Post>((emit) => {const onAdd = (data: Post) => {// emit data to clientemit.next(data);};// trigger `onAdd()` when `add` is triggered in our event emitteree.on('add', onAdd);// unsubscribe function when client disconnects or stops subscribingreturn () => {ee.off('add', onAdd);};});}),add: t.procedure.input(z.object({id: z.string().uuid().optional(),text: z.string().min(1),}),).mutation(async (opts) => {const post = { ...opts.input }; /* [..] add to db */ee.emit('add', post);return post;}),});
server/router.tstsx
import { EventEmitter } from 'events';import { initTRPC } from '@trpc/server';import { observable } from '@trpc/server/observable';import { z } from 'zod';// create a global event emitter (could be replaced by redis, etc)const ee = new EventEmitter();const t = initTRPC.create();export const appRouter = t.router({onAdd: t.procedure.subscription(() => {// return an `observable` with a callback which is triggered immediatelyreturn observable<Post>((emit) => {const onAdd = (data: Post) => {// emit data to clientemit.next(data);};// trigger `onAdd()` when `add` is triggered in our event emitteree.on('add', onAdd);// unsubscribe function when client disconnects or stops subscribingreturn () => {ee.off('add', onAdd);};});}),add: t.procedure.input(z.object({id: z.string().uuid().optional(),text: z.string().min(1),}),).mutation(async (opts) => {const post = { ...opts.input }; /* [..] add to db */ee.emit('add', post);return post;}),});
WebSocketサーバーの作成
bash
yarn add ws
bash
yarn add ws
server/wsServer.tsts
import { applyWSSHandler } from '@trpc/server/adapters/ws';import ws from 'ws';import { appRouter } from './routers/app';import { createContext } from './trpc';const wss = new ws.Server({port: 3001,});const handler = applyWSSHandler({ wss, router: appRouter, createContext });wss.on('connection', (ws) => {console.log(`➕➕ Connection (${wss.clients.size})`);ws.once('close', () => {console.log(`➖➖ Connection (${wss.clients.size})`);});});console.log('✅ WebSocket Server listening on ws://:3001');process.on('SIGTERM', () => {console.log('SIGTERM');handler.broadcastReconnectNotification();wss.close();});
server/wsServer.tsts
import { applyWSSHandler } from '@trpc/server/adapters/ws';import ws from 'ws';import { appRouter } from './routers/app';import { createContext } from './trpc';const wss = new ws.Server({port: 3001,});const handler = applyWSSHandler({ wss, router: appRouter, createContext });wss.on('connection', (ws) => {console.log(`➕➕ Connection (${wss.clients.size})`);ws.once('close', () => {console.log(`➖➖ Connection (${wss.clients.size})`);});});console.log('✅ WebSocket Server listening on ws://:3001');process.on('SIGTERM', () => {console.log('SIGTERM');handler.broadcastReconnectNotification();wss.close();});
TRPCClient
をWebSocketを使用するように設定
ヒント
リンクを使用して、クエリとミューテーションをHTTPトランスポートに、サブスクリプションをWebSocketにルーティングできます。
client.tstsx
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';// create persistent WebSocket connectionconst wsClient = createWSClient({url: `ws://:3001`,});// configure TRPCClient to use WebSockets transportconst client = createTRPCClient<AppRouter>({links: [wsLink({client: wsClient,}),],});
client.tstsx
import { createTRPCClient, createWSClient, wsLink } from '@trpc/client';import type { AppRouter } from '../path/to/server/trpc';// create persistent WebSocket connectionconst wsClient = createWSClient({url: `ws://:3001`,});// configure TRPCClient to use WebSockets transportconst client = createTRPCClient<AppRouter>({links: [wsLink({client: wsClient,}),],});
Reactの使用
/examples/next-prisma-starter-websocketsを参照してください。
WebSockets RPC仕様
TypeScript定義を詳しく調べて、詳細を確認できます。
query
/mutation
リクエスト
ts
{id: number | string;jsonrpc?: '2.0'; // optionalmethod: 'query' | 'mutation';params: {path: string;input?: unknown; // <-- pass input of procedure, serialized by transformer};}
ts
{id: number | string;jsonrpc?: '2.0'; // optionalmethod: 'query' | 'mutation';params: {path: string;input?: unknown; // <-- pass input of procedure, serialized by transformer};}
レスポンス
…以下、またはエラー。
ts
{id: number | string;jsonrpc?: '2.0'; // only defined if included in requestresult: {type: 'data'; // always 'data' for mutation / queriesdata: TOutput; // output from procedure}}
ts
{id: number | string;jsonrpc?: '2.0'; // only defined if included in requestresult: {type: 'data'; // always 'data' for mutation / queriesdata: TOutput; // output from procedure}}
subscription
/subscription.stop
サブスクリプションの開始
ts
{id: number | string;jsonrpc?: '2.0';method: 'subscription';params: {path: string;input?: unknown; // <-- pass input of procedure, serialized by transformer};}
ts
{id: number | string;jsonrpc?: '2.0';method: 'subscription';params: {path: string;input?: unknown; // <-- pass input of procedure, serialized by transformer};}
サブスクリプションをキャンセルするには、subscription.stop
を呼び出します
ts
{id: number | string; // <-- id of your created subscriptionjsonrpc?: '2.0';method: 'subscription.stop';}
ts
{id: number | string; // <-- id of your created subscriptionjsonrpc?: '2.0';method: 'subscription.stop';}
サブスクリプションレスポンスの形式
…以下、またはエラー。
ts
{id: number | string;jsonrpc?: '2.0';result: (| {type: 'data';data: TData; // subscription emitted data}| {type: 'started'; // subscription started}| {type: 'stopped'; // subscription stopped})}
ts
{id: number | string;jsonrpc?: '2.0';result: (| {type: 'data';data: TData; // subscription emitted data}| {type: 'started'; // subscription started}| {type: 'stopped'; // subscription stopped})}
エラー
https://www.jsonrpc.org/specification#error_objectまたはエラーのフォーマットを参照してください。
サーバーからクライアントへの通知
{ id: null, type: 'reconnect' }
サーバーをシャットダウンする前に、クライアントに再接続するように指示します。wssHandler.broadcastReconnectNotification()
によって呼び出されます。