name: instantdb
description: 与 InstantDB 的实时数据库集成。在处理 InstantDB 应用时使用此技能,以执行管理操作(创建/更新/删除实体、链接/取消链接关系、查询数据)并订阅实时数据变更。触发条件包括提及 InstantDB、实时更新、数据库同步、实体操作,或当 OpenClaw 需要向人类实时发送可见的操作更新时。
用于 InstantDB 的 Node.js 集成,使 OpenClaw 能够执行管理操作并通过 WebSocket 订阅监控实时数据变更。
安装依赖:
npm install
设置环境变量:
export INSTANTDB_APP_ID="your-app-id"
export INSTANTDB_ADMIN_TOKEN="your-admin-token"
使用 InstantDB 查询语法获取数据:
const { InstantDBClient } = require('./scripts/instantdb.js');
const client = new InstantDBClient(appId, adminToken);
const result = await client.query({
tasks: {
$: {
where: { status: 'active' }
}
}
});
命令行:
./scripts/instantdb.js query '{"tasks": {}}'
向命名空间添加新实体:
const { entityId, result } = await client.createEntity('tasks', {
title: 'Process data',
status: 'pending',
priority: 'high'
});
命令行:
./scripts/instantdb.js create tasks '{"title": "Process data", "status": "pending"}'
可选实体 ID:
./scripts/instantdb.js create tasks '{"title": "Task"}' custom-entity-id
修改现有实体的属性:
await client.updateEntity(entityId, 'tasks', {
status: 'completed'
});
命令行:
./scripts/instantdb.js update <entity-id> tasks '{"status": "completed"}'
移除实体:
await client.deleteEntity(entityId, 'tasks');
命令行:
./scripts/instantdb.js delete <entity-id> tasks
在实体间创建关系:
await client.linkEntities(taskId, assigneeId, 'assignees');
命令行:
./scripts/instantdb.js link <parent-id> <child-id> assignees
移除实体间的关系:
await client.unlinkEntities(taskId, assigneeId, 'assignees');
命令行:
./scripts/instantdb.js unlink <parent-id> <child-id> assignees
通过 WebSocket 监控数据变更:
const subscriptionId = client.subscribe(
{ tasks: { $: { where: { status: 'active' } } } },
(data) => {
console.log('数据已更新:', data);
},
(error) => {
console.error('订阅错误:', error);
}
);
// 稍后:client.unsubscribe(subscriptionId);
命令行(监听指定时长):
./scripts/instantdb.js subscribe '{"tasks": {}}' 60 # 监听 60 秒
使用事务构建器原子化执行多个操作:
const { tx, id } = require('@instantdb/admin');
await client.transact([
tx.tasks[id()].update({ title: 'Task 1' }),
tx.tasks[id()].update({ title: 'Task 2' })
]);
命令行:
./scripts/instantdb.js transact '[{"op": "update", "id": "...", "data": {...}}]'
向人类观察者实时发送进度:
const { id } = require('@instantdb/admin');
// 创建状态实体
const actionId = id();
await client.createEntity('actions', {
type: 'file_processing',
status: 'started',
progress: 0,
timestamp: Date.now()
}, actionId);
// 更新进度
await client.updateEntity(actionId, 'actions', {
progress: 50,
status: 'processing'
});
// 标记完成
await client.updateEntity(actionId, 'actions', {
progress: 100,
status: 'completed'
});
追踪复杂操作:
const { tx, id } = require('@instantdb/admin');
const workflowId = id();
const steps = ['Extract', 'Transform', 'Validate', 'Load', 'Verify'];
// 初始化工作流并链接步骤
const txs = [
tx.workflows[workflowId].update({
name: 'Data Pipeline',
status: 'running',
currentStep: 1,
totalSteps: steps.length
})
];
const stepIds = steps.map((name, i) => {
const stepId = id();
txs.push(
tx.steps[stepId].update({
name,
order: i + 1,
status: 'pending'
}),
tx.workflows[workflowId].link({ steps: stepId })
);
return stepId;
});
await client.transact(txs);
// 随着步骤完成而更新
for (let i = 0; i < stepIds.length; i++) {
await client.updateEntity(stepIds[i], 'steps', {
status: 'completed'
});
await client.updateEntity(workflowId, 'workflows', {
currentStep: i + 2
});
}
人类订阅以观察 OpenClaw 的操作:
// 人类的前端代码
import { init } from '@instantdb/react';
const db = init({ appId });
function ActionMonitor() {
const { data } = db.useQuery({
actions: {
$: {
where: { status: { in: ['started', 'processing'] } }
}
}
});
return data?.actions?.map(action => (
<div key={action.id}>
{action.type}: {action.progress}%
</div>
));
}
对于长时间运行的操作,流式更新进度:
const { id } = require('@instantdb/admin');
async function processLargeDataset(items) {
const progressId = id();
await client.createEntity('progress', {
total: items.length,
completed: 0,
status: 'running'
}, progressId);
for (let i = 0; i < items.length; i++) {
// 处理项目...
await processItem(items[i]);
// 每处理 10 个项目更新一次
if (i % 10 === 0) {
await client.updateEntity(progressId, 'progress', {
completed: i + 1,
percentage: Math.round(((i + 1) / items.length) * 100)
});
}
}
await client.updateEntity(progressId, 'progress', {
completed: items.length,
percentage: 100,
status: 'completed'
});
}
详见 references/transactions.md,其中包含:
- 批量操作
- 关系管理
- 条件更新
- 状态机
- 级联操作
所有操作均返回 Promise,失败时会拒绝:
try {
const result = await client.createEntity('tasks', data);
} catch (error) {
console.error('操作失败:', error.message);
}
详见 references/query_syntax.md,其中包含全面的查询示例:
- Where 子句和运算符
- 关系遍历
- 排序和分页
- 多级嵌套
references/query_syntax.mdreferences/transactions.md