mcpField
R
rivetkit-client-javascript

rivetkit-client-javascript

github.com/pedronauck开发64865 次安装2 天前更新
代码仓库

关于 rivetkit-client-javascript

rivetkit-client-javascript 是面向浏览器、Node.js 和 Bun 开发者的技能,介绍如何用 `rivetkit/client` 连接 Rivet Actors。涵盖 Actor 操作、事件订阅及 HTTP 和 WebSocket 访问。

主要功能

  1. 01创建 JavaScript 客户端
  2. 02创建或获取 Actor
  3. 03调用 Actor 操作
  4. 04订阅事件并监听连接生命周期
  5. 05直接访问 HTTP 和 WebSocket

适用场景

  1. 01从浏览器调用计数器 Actor
  2. 02在 Node.js 或 Bun 后端调用 Actor
  3. 03订阅聊天房间消息
  4. 04直接获取 Actor 的 HTTP 响应

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/pedronauck/skills --skill rivetkit-client-javascript

安装后在 Claude Code 中输入/rivetkit-client-javascript确认已加载。

附带文件index.json

详细介绍

RivetKit JavaScript 客户端

构建 JavaScript 客户端(浏览器、Node.js 或 Bun)并通过 rivetkit/client 连接 Rivet Actors 时,请使用此 skill。

入门步骤

  1. 安装客户端(最新版本:2.1.0-rc.2)
    npm install [email protected]
    
  2. 使用 createClient() 创建客户端并调用 Actor 操作。

错误处理策略

  • 默认优先采用快速失败行为。
  • 除非绝对必要,否则避免使用 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);

获取 Actor

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 的 Actor,请直接调用它们:

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);
  }
}

概念

键

键用于唯一标识 Actor 实例。使用复合键(数组)进行分层寻址:

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_NAMESPACE
  • RIVET_TOKEN
  • RIVET_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 客户端概览。

需要了解客户端以外的内容?

如果你需要了解更多关于 Rivet Actors、注册表或服务端 RivetKit 的内容,请添加主 skill:

npx skills add rivet-dev/skills

然后使用 rivetkit skill 获取后端指导。

评论

支持 Markdown