OA0 = Omni AI 0
OA0 是一个探索 AI 的论坛
现在注册
已注册用户请  登录
OA0  ›  技能包  ›  instantdb: 与 InstantDB 的实时数据库集成

instantdb: 与 InstantDB 的实时数据库集成

 
  network ·  2026-02-01 12:17:15 · 3 次点击  · 0 条评论  

name: instantdb
description: 与 InstantDB 的实时数据库集成。在处理 InstantDB 应用时使用此技能,以执行管理操作(创建/更新/删除实体、链接/取消链接关系、查询数据)并订阅实时数据变更。触发条件包括提及 InstantDB、实时更新、数据库同步、实体操作,或当 OpenClaw 需要向人类实时发送可见的操作更新时。


InstantDB 集成

概述

用于 InstantDB 的 Node.js 集成,使 OpenClaw 能够执行管理操作并通过 WebSocket 订阅监控实时数据变更。

设置

安装依赖:

npm install

设置环境变量:

export INSTANTDB_APP_ID="your-app-id"
export INSTANTDB_ADMIN_TOKEN="your-admin-token"

核心功能

1. 查询数据

使用 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": {}}'

2. 创建实体

向命名空间添加新实体:

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

3. 更新实体

修改现有实体的属性:

await client.updateEntity(entityId, 'tasks', {
  status: 'completed'
});

命令行:

./scripts/instantdb.js update <entity-id> tasks '{"status": "completed"}'

4. 删除实体

移除实体:

await client.deleteEntity(entityId, 'tasks');

命令行:

./scripts/instantdb.js delete <entity-id> tasks

5. 链接实体

在实体间创建关系:

await client.linkEntities(taskId, assigneeId, 'assignees');

命令行:

./scripts/instantdb.js link <parent-id> <child-id> assignees

6. 取消链接实体

移除实体间的关系:

await client.unlinkEntities(taskId, assigneeId, 'assignees');

命令行:

./scripts/instantdb.js unlink <parent-id> <child-id> assignees

7. 实时订阅

通过 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 秒

8. 事务

使用事务构建器原子化执行多个操作:

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": {...}}]'

OpenClaw 使用模式

操作状态更新

向人类观察者实时发送进度:

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 子句和运算符
- 关系遍历
- 排序和分页
- 多级嵌套

参考

  • InstantDB 文档:https://www.instantdb.com/docs
  • 管理 SDK:https://www.instantdb.com/docs/admin
  • 查询参考:见 references/query_syntax.md
  • 事务模式:见 references/transactions.md
3 次点击  ∙  0 人收藏  
登录后收藏  
目前尚无回复
0 条回复
About   ·   Help   ·    
OA0 - Omni AI 0 一个探索 AI 的社区
沪ICP备2024103595号-2
Developed with Cursor