rivetkit-client-javascript について
ブラウザー、Node.js、Bun から `rivetkit/client` で Rivet Actors に接続する開発者向けのスキルです。Actor のアクション、イベント購読、HTTP と WebSocket の直接利用を扱います。
主な機能
- 01JavaScript クライアントの作成
- 02Actor の作成または取得
- 03Actor アクションの呼び出し
- 04イベント購読と接続状態の監視
- 05HTTP と WebSocket への直接アクセス
活用シーン
- 01ブラウザーからカウンター Actor を呼び出す
- 02Node.js または Bun のバックエンドから Actor を呼び出す
- 03チャットルームのメッセージを購読する
- 04Actor の HTTP 応答を直接取得する
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ pedronauck/ skills --skill rivetkit-client-javascriptインストール後、Claude Code で/rivetkit-client-javascriptを入力して読み込まれたか確認します。
同梱ファイルindex.json
詳細
RivetKit JavaScript クライアント
rivetkit/client を使用して Rivet Actors に接続する JavaScript クライアント(ブラウザー、Node.js、Bun)を構築する際に、このスキルを使用してください。
はじめに
- クライアントをインストールします(最新版:2.1.0-rc.2)
npm install [email protected] createClient()でクライアントを作成し、アクターのアクションを呼び出します。
エラー処理ポリシー
- デフォルトでは、フェイルファストの動作を優先してください。
- 絶対に必要な場合を除き、
try/catchは避けてください。 catchを使用する場合は、少なくともエラーをログに記録するなど、明示的に処理してください。
はじめに
使い始めるには、バックエンドのクイックスタートガイドを参照してください。
最小限のクライアント
import { createClient } from "rivetkit/client";
import type { registry } from "./actors";
const client = createClient<typeof registry>({
endpoint: "https://my-namespace:[email protected]",
});
const counter = client.counter.getOrCreate(["my-counter"]);
const count = await counter.increment(1);
import { actor, setup } from "rivetkit";
export const counter = actor({
state: { count: 0 },
actions: {
increment: (c, x: number) => {
c.state.count += x;
return c.state.count;
},
},
});
export const registry = setup({
use: { counter },
});
ステートレスとステートフル
import { createClient } from "rivetkit/client";
const client = createClient();
const handle = client.counter.getOrCreate(["my-counter"]);
// Stateless: each call is independent
await handle.increment(1);
// Stateful: keep a connection open for realtime events
const conn = handle.connect();
conn.on("count", (value: number) => console.log(value));
await conn.increment(1);
アクターの取得
import { createClient } from "rivetkit/client";
const client = createClient();
const room = client.chatRoom.getOrCreate(["room-42"]);
const existing = client.chatRoom.get(["room-42"]);
const created = await client.game.create(["game-1"], {
input: { mode: "ranked" },
});
const byId = client.chatRoom.getForId("actor-id");
const resolvedId = await room.resolve();
接続パラメーター
import { createClient } from "rivetkit/client";
const client = createClient();
const chat = client.chatRoom.getOrCreate(["general"], {
params: { authToken: "jwt-token-here" },
});
const conn = chat.connect();
イベントのサブスクライブ
import { createClient } from "rivetkit/client";
const client = createClient();
const conn = client.chatRoom.getOrCreate(["general"]).connect();
conn.on("message", (msg: string) => console.log(msg));
conn.once("gameOver", () => console.log("done"));
接続のライフサイクル
import { createClient } from "rivetkit/client";
const client = createClient();
const conn = client.chatRoom.getOrCreate(["general"]).connect();
conn.onOpen(() => console.log("connected"));
conn.onClose(() => console.log("disconnected"));
conn.onError((err) => console.error("error:", err));
conn.onStatusChange((status) => console.log("status:", status));
await conn.dispose();
低レベル HTTP と WebSocket
onRequest または onWebSocket を実装するアクターは、直接呼び出してください。
import { createClient } from "rivetkit/client";
const client = createClient();
const handle = client.chatRoom.getOrCreate(["general"]);
const response = await handle.fetch("history");
const history = await response.json();
const ws = await handle.webSocket("stream");
ws.addEventListener("message", (event) => {
console.log("message:", event.data);
});
ws.send("hello");
バックエンドからの呼び出し
import { Hono } from "hono";
import { createClient } from "rivetkit/client";
const app = new Hono();
const client = createClient();
app.post("/increment/:name", async (c) => {
const counterHandle = client.counter.getOrCreate([c.req.param("name")]);
const newCount = await counterHandle.increment(1);
return c.json({ count: newCount });
});
エラー処理
import { ActorError } from "rivetkit/client";
import { createClient } from "rivetkit/client";
const client = createClient();
try {
await client.user.getOrCreate(["user-123"]).updateUsername("ab");
} catch (error) {
if (error instanceof ActorError) {
console.log(error.code, error.metadata);
}
}
概念
キー
キーはアクターインスタンスを一意に識別します。階層的にアドレス指定するには、複合キー(配列)を使用します。
import { createClient } from "rivetkit/client";
import type { registry } from "./actors";
const client = createClient<typeof registry>();
// Compound key: [org, room]
client.chatRoom.getOrCreate(["org-acme", "general"]);
import { actor, setup } from "rivetkit";
export const chatRoom = actor({
state: { messages: [] as string[] },
actions: {
getRoomInfo: (c) => ({ org: c.key[0], room: c.key[1] }),
},
});
export const registry = setup({
use: { chatRoom },
});
userId にユーザーデータが含まれる場合、"org:${userId}" のような文字列補間でキーを作成しないでください。キーインジェクション攻撃を防ぐため、代わりに配列を使用してください。
環境変数
createClient() は次の環境変数を自動的に読み取ります。
RIVET_ENDPOINT(エンドポイント)RIVET_NAMESPACERIVET_TOKENRIVET_RUNNER
未設定の場合、ブラウザーでは window.location.origin + "/api/rivet"、サーバーでは http://127.0.0.1:6420 がデフォルトになります。
エンドポイント形式
エンドポイントでは URL 認証構文を使用できます。
https://namespace:[email protected]
エンドポイントに認証情報を含めず、RIVET_NAMESPACE と RIVET_TOKEN を個別に指定することもできます。サーバーレス環境にデプロイする場合は、アプリの /api/rivet URL を使用してください。詳しくは、エンドポイントを参照してください。
API リファレンス
パッケージ: rivetkit
RivetKit クライアントの概要を参照してください。
createClient- クライアントを作成しますcreateEngineDriver- エンジンドライバーDriverConfig- ドライバー設定Client- クライアント型
クライアント以外の情報も必要ですか?
Rivet Actors、レジストリー、またはサーバーサイドの RivetKit について詳しく知りたい場合は、メインスキルを追加してください。
npx skills add rivet-dev/skills
その後、バックエンドのガイダンスには rivetkit スキルを使用してください。