Server SDK(Node.js)
Node 后端 / Worker / CLI / 自动化脚本以项目 API Key 调用 Server SDK(agentbase-node-sdk)。API Key 按最小 scope 授权,请求跳过行级权限检查(hasRole)——可管理全库数据,因此只存在于受控服务端,绝不进浏览器/客户端/Sites 前端。Java / Python / Go 面见同目录 java.md / python.md / go.md;浏览器前端用 Client SDK;治理自动化用 Console SDK。
安装与初始化
npm install agentbase-node-sdk@2.10.0 --save-exactimport { Client, TablesDB } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint('https://appbuild.oceanbase.com/v1') // SIT: https://appbuild-sit.oceanbase.com/v1
.setProject('<PROJECT_ID>')
.setKey('<API_KEY>'); // X-Appwrite-Key
const tablesDB = new TablesDB(client); // 服务逐个构造环境变量惯例:APPWRITE_ENDPOINT / APPWRITE_PROJECT_ID / APPWRITE_API_KEY(+ dotenv);自签名实例加 .setSelfSigned(true)。安全底线:行过滤条件在服务端生成,不信任前端传入的 queries。
5 分钟上手
初始化(上文);API Key 在项目 Overview → API keys 创建,按需选最小 scope。
建表并写入一行:
import { ID } from 'agentbase-node-sdk';
await tablesDB.createTable({
databaseId: 'app-db', tableId: 'tasks', name: 'Tasks',
rowSecurity: true,
columns: [{ key: 'title', type: 'varchar', size: 256, required: true }],
});
await tablesDB.createRow('app-db', 'tasks', ID.unique(), { title: '写周报' });为前端用户发登录令牌:
users.createToken('<userId>')→ 客户端account.createSession({ userId, secret })(见下节)。
Custom Token 签发入口
服务端:
users.createToken('<userId>')→ 返回{ secret, expire }。客户端(client-sdk/web.md):
account.createSession({ userId, secret })完成 Custom Token 登录。
注意区分:Tokens 服务是 Storage 文件临时令牌(createFileToken),与用户令牌无关;users.createJWT / account.createJWT 是给用户签发短期 JWT(约 15 分钟),用于服务间带用户身份调用,不是 Session 通道。
客户端初始化与鉴权方法全集
Client 实例承载连接配置与请求头组装,所有服务类(new TablesDB(client)、new KnowledgeBases(client) 等)共享同一个 Client 实例即可:
Client 方法 | 注入的 HTTP 请求头 | 适用场景与安全约束 |
|---|---|---|
setEndpoint(url) | —(请求基准地址) | 必填,形如 https://appbuild-sit.oceanbase.com/v1 或 https://appbuild.oceanbase.com/v1。 |
setProject(projectId) | X-Appwrite-Project | 必填,指定目标项目 ID(如演示项目 enterprise-ai-hub-210)。 |
setKey(apiKey) | X-Appwrite-Key | 服务端主用鉴权方式,跳过 RLS(hasRole),受所选 scopes[] 约束。 |
setJWT(jwt) | X-Appwrite-JWT | 服务端代表特定登录用户调用数据面接口(受该用户 RLS 行级权限约束,有效期约 15 分钟)。 |
setSession(session) | X-Appwrite-Session | 服务端 SSR(如 Next.js / SvelteKit)转发浏览器会话 Cookie 时装载用户会话。 |
setLocale(locale) | X-Appwrite-Locale | 指定国际化返回语种(如 zh-CN、en-US、ja-JP)。 |
setSelfSigned(true) | —(TLS 校验开关) | 仅用于自签名证书的私有测试实例,生产环境严禁开启。 |
addHeader(key, val) | 自定义请求头 | 注入链路追踪头(如 traceparent)或网关自定义幂等头。 |
游标分页、文件上传与流式下载范式
在生产环境中处理大表遍历、富文档上传与原文下载时,应遵循以下标准写法:
import { Client, TablesDB, Storage, Query, ID, AgentbaseException } from 'agentbase-node-sdk';
import { InputFile } from 'agentbase-node-sdk/file';
import { writeFileSync } from 'node:fs';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1')
.setProject(process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210')
.setKey(process.env.APPBASE_API_KEY!);
const tablesDB = new TablesDB(client);
const storage = new Storage(client);
// 1. 游标分页遍历大表(推荐用 Query.cursorAfter 替代大 offset,避免深分页性能衰减)
async function iterateAllTickets() {
let lastId: string | null = null;
const pageSize = 100;
while (true) {
const queries = [
Query.equal('status', ['open', 'in_progress']),
Query.orderAsc('$id'),
Query.limit(pageSize),
];
if (lastId) {
queries.push(Query.cursorAfter(lastId));
}
const page = await tablesDB.listRows({
databaseId: 'enterprise_biz_db',
tableId: 'customer_tickets',
queries,
total: false, // 关闭 count(*) 统计以显著降低大表查询开销
});
for (const row of page.rows) {
console.log('处理工单:', row.$id, row.title);
}
if (page.rows.length < pageSize) break;
lastId = page.rows[page.rows.length - 1].$id;
}
}
// 2. 上传本地文件或内存 Buffer 到 Storage 桶(如知识库源文件桶 kb_enterprise_docs)
async function uploadSopDocument() {
const file = await storage.createFile({
bucketId: 'kb_enterprise_docs',
fileId: ID.unique(),
file: InputFile.fromPlainText(
'# 智能客服 SOP 标准作业手册\n1. 首响时效不超过 30 秒...',
'智能客服SOP标准作业手册.md'
),
});
// 下载文件二进制字节流(返回 ArrayBuffer)
const bytes = await storage.getFileDownload({
bucketId: 'kb_enterprise_docs',
fileId: file.$id,
});
writeFileSync('/tmp/sop-downloaded.md', Buffer.from(bytes));
}生产级错误处理与指数退避重试
所有 SDK 调用异常统一抛出 AgentbaseException,包含 code(HTTP 状态码)、type(平台错误码字符串,如 row_already_exists、rate_limit_exceeded、project_database_read_only)与 response(原始响应文本):
import { AgentbaseException } from 'agentbase-node-sdk';
export async function withRetry<T>(fn: () => Promise<T>, maxAttempts = 3): Promise<T> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return await fn();
} catch (err) {
if (err instanceof AgentbaseException) {
// 400 / 401 / 403 / 404 / 409 属于确定性业务或权限错误,直接抛出不重试
const retryable = err.code === 429 || err.code === 502 || err.code === 503 || err.code === 504;
if (!retryable || attempt === maxAttempts) {
throw err;
}
const delayMs = Math.min(1000 * 2 ** (attempt - 1), 8000);
await new Promise((r) => setTimeout(r, delayMs));
continue;
}
throw err;
}
}
throw new Error('Unreachable');
}功能面导航
| 服务 | 覆盖 | 功能文档 |
|---|---|---|
TablesDB | 库/表/列/索引/行 CRUD、事务、aggregateRows 行聚合、updateColumnComment | ../databases.md |
Databases / DocumentsDB | 旧文档面(新项目优先 TablesDB) | ../databases.md |
Storage | 桶与文件 CRUD、下载/预览/查看 | ../storage.md |
Functions | 创建/部署(tar 上传、VCS、模板、duplicate)、执行、变量、运行时与规格查询 | ../functions.md |
Sites | 站点与部署全集(构建/变量/框架规格/日志) | ../sites.md |
Users | 项目用户全生命周期 + createToken + Target/JWT/MFA | ../users.md |
Teams | 项目内团队与成员 | ../teams.md |
Messaging | Email/Push/SMS、Topic、Subscriber、Provider | ../messaging.md |
Account / Projects / Project | 账号 quota 读写与覆盖项目列表;项目设置与变量、组织治理查询;项目级 quota 需 Console SDK 或 REST | ../limits.md |
Memory / KnowledgeBases | 记忆 / RAG 数据面全集 | ../memory.md、../knowledge-bases.md |
LlmGateway / AiGateway | 模型 Provider/Key + 执行;统一 AI 数据面控制面 | ../llm-gateway.md、../ai-gateway.md |
Observability / Moderation | 上报(≤100/批、207)与查询;审核配置与日志 | ../observability.md、../moderation.md |
Webhooks / Graphql / Avatars / Locale / Health / Tokens | 横切服务与文件临时令牌 | ../misc/webhooks.md |
| —— | 无 Sql 服务:SQL 走 HTTP 形态或 Console SDK(../databases/sql-proxy.md);无 Realtime:实时推送是客户端能力(../realtime.md) |
与 Console SDK 并用
Server SDK 的服务面已覆盖全量项目功能,但以下场景需要 Console SDK 补位:
Console-only 操作:创建项目/Team、
projects.createPlatform平台注册(项目 Key 无platforms.*scope)、组织与账单、Admin/Backups。Sql服务:仅 Console SDK 提供(或走 HTTPPOST {endpoint}/sql)。/limits限频接口:无 typed 封装时用 Console SDKclient.call或 REST。组织级用量:
organizations.listUsageAggregates仅 Console SDK。
Node 同进程并用:npm i agentbase-node-sdk@2.10.0 agentbase-console-sdk@2.10.0 --save-exact,各自 new Client() 按需装载 Key/Session。
错误与边界
AgentbaseException:code为 HTTP 状态码、type为错误类型串;413(存储超限)、429(限频)、401/403(Key/scope)见各功能页。2.6.0 安全默认值:Function API Key 不接受 query string 传递;外部 URL 拒绝本机/私网/元数据地址。
示例指引
Node 完整调用写法:../examples/javascript.md