关于 surrealdb-js
surrealdb-js 是使用官方 SurrealDB JavaScript SDK 的技能,面向在 Node.js、Deno、Bun 和浏览器中开发的用户。内容涵盖远程及嵌入式连接、数据库操作和实时查询。
主要功能
- 01连接远程或嵌入式数据库
- 02选择命名空间和数据库
- 03验证数据库用户身份
- 04执行 CRUD 与 SurrealQL 查询
- 05订阅表的实时变更
适用场景
- 01使用 SurrealDB 构建 JavaScript 应用
- 02执行参数化 SurrealQL 查询
- 03响应表的实时变更
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ surrealdb/ agent-skills --skill surrealdb-js安装后在 Claude Code 中输入/surrealdb-js确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
references/data-types.mdembedded.mdlive-queries.md详细介绍
SurrealDB JavaScript SDK
官方 SDK(npm 上的 surrealdb)可在 Node.js、Deno、Bun 和浏览器中运行。它通过 WebSocket/HTTP 连接远程 SurrealDB 实例,也可以在进程内运行嵌入式引擎。请使用 surrealdb 最新稳定版;除非用户要求特定版本,否则安装时不要指定版本(npm i surrealdb)。
安装
npm i surrealdb
# or: pnpm i surrealdb / yarn add surrealdb / bun add surrealdb
连接并选择命名空间/数据库
始终先 connect,再使用 use 选择命名空间和数据库,然后进行身份验证。完成后关闭连接。
import { Surreal } from "surrealdb";
const db = new Surreal();
await db.connect("ws://127.0.0.1:8000/rpc");
await db.use({ namespace: "test", database: "test" });
await db.signin({ username: "root", password: "root" });
// ... work ...
await db.close();
使用 surreal start -u root -p root rocksdb:mydb 运行本地服务(或使用 surreal start -u root -p root 在内存中运行)。如需在进程内运行 SurrealDB 且无需服务端,请参阅 references/embedded.md。
身份验证
// Root / namespace / database users
await db.signin({ username: "root", password: "root" });
await db.signin({ namespace: "test", username: "ns_user", password: "..." });
await db.signin({ namespace: "test", database: "test", username: "db_user", password: "..." });
// Record (scope) access — sign in / sign up against a DEFINE ACCESS method
const token = await db.signin({
namespace: "test",
database: "test",
access: "user", // name of the access method
variables: { email: "[email protected]", pass: "secret" },
});
await db.signup({
namespace: "test",
database: "test",
access: "user",
variables: { email: "[email protected]", pass: "secret" },
});
await db.authenticate(token); // re-auth with a stored JWT
await db.invalidate(); // log out the current session
const me = await db.info(); // info about the authenticated record user
CRUD
将表名作为字符串("person")传入,或传入特定记录的 RecordId。有关 RecordId、Table、Duration、Decimal 和其他值类,请参阅 references/data-types.md。
import { RecordId } from "surrealdb";
interface Person { id: RecordId; name: string; age?: number; }
// Create (random id, or a specific RecordId)
await db.create<Person>("person", { name: "Tobie" });
await db.create<Person>(new RecordId("person", "tobie"), { name: "Tobie" });
// Select all from a table, or a single record
const people = await db.select<Person>("person");
const tobie = await db.select<Person>(new RecordId("person", "tobie"));
// Replace the whole record(s)
await db.update<Person>(new RecordId("person", "tobie"), { name: "Tobie", age: 30 });
// Insert or update (upsert)
await db.upsert<Person>(new RecordId("person", "tobie"), { name: "Tobie" });
// Merge partial data into record(s)
await db.merge<Person>("person", { active: true });
// JSON Patch a record
await db.patch(new RecordId("person", "tobie"), [
{ op: "replace", path: "/name", value: "Tobie M H" },
]);
// Bulk insert
await db.insert<Person>("person", [{ name: "A" }, { name: "B" }]);
// Graph relation: person:tobie ->wrote-> article:surreal
await db.relate(new RecordId("person", "tobie"), "wrote", new RecordId("article", "surreal"));
// Delete record(s)
await db.delete("person");
await db.delete(new RecordId("person", "tobie"));
查询
db.query<T>(sql, vars) 执行原始 SurrealQL,并返回每条语句对应一个条目的数组。始终通过绑定参数传递用户输入,切勿使用字符串插值。
const [people, count] = await db.query<[Person[], number]>(
`SELECT * FROM person WHERE age > $min;
SELECT count() FROM person GROUP ALL;`,
{ min: 18 },
);
// Bind values and RecordIds as parameters
const [found] = await db.query<[Person[]]>(
"SELECT * FROM person WHERE id = $who",
{ who: new RecordId("person", "tobie") },
);
其他辅助方法:db.let(name, value) / db.unset(name) 设置会话参数,以便在后续查询中作为 $name 使用;db.run(fnName, version, args) 调用已定义的函数;db.queryRaw() 返回未经解析的 RPC 响应(每条语句的状态和耗时)。
实时查询
使用 db.live() 订阅表的实时变更。需要 WebSocket(或嵌入式)连接,不支持 HTTP。请参阅 references/live-queries.md。
const queryUuid = await db.live<Person>("person", (action, result) => {
// action: "CREATE" | "UPDATE" | "DELETE" | "CLOSE"
console.log(action, result);
});
await db.kill(queryUuid); // stop the subscription
参考资料
- references/data-types.md —
RecordId、Table、Duration、Decimal、Uuid、几何类型和 CBOR 映射。 - references/embedded.md — 通过
@surrealdb/node(RocksDB / SurrealKV / 内存)和@surrealdb/wasm(内存 / IndexedDB)使用嵌入式引擎。 - references/live-queries.md —
live、subscribeLive和kill用法。