npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@seaverse/data-sdk

v0.1.0

Published

SeaVerse Data SDK - PostgreSQL/AlloyDB data operations with RLS-based permissions

Readme

@seaverse/data-sdk

npm version License: MIT

高性能数据服务 SDK,基于 PostgreSQL/AlloyDB + PostgREST + RLS 架构。

🚀 核心概念

App ID 是什么?

App ID 是您在 SeaVerse 平台上创建的应用的唯一标识符。它用于:

  • ✅ 多租户数据隔离(每个应用的数据互不干扰)
  • ✅ 权限控制(RLS 策略基于 app_id)
  • ✅ 资源配额管理

如何获取 App ID?

  1. 登录 SeaVerse 控制台
  2. 进入"应用管理"
  3. 复制您的 App ID

⚠️ 重要:所有 SDK 操作都需要提供有效的 appId,否则无法访问数据。

特性

  • ✅ TypeScript 类型支持
  • ✅ 自动处理 JWT 认证
  • ✅ RLS 安全控制
  • ✅ 应用隔离
  • ✅ 简单易用的 API
  • ✅ 完整的错误处理
  • ✅ 支持过滤、排序、分页
  • ✅ 支持标签和 JSONB 字段查询

安装

npm install @seaverse/data-sdk

快速开始

1. 初始化 SDK

SDK 提供三种初始化方式,根据您的使用场景选择:

import { DataClient } from '@seaverse/data-sdk';

// 方式1: SeaVerse 平台应用(自动检测环境)- 推荐
// 适用于部署在 SeaVerse 平台的应用
const client = new DataClient({
  appId: 'my-app-123',         // 必需:应用ID
  token: 'user-jwt-token',      // 必需:用户JWT token
});

// 方式2: 第三方应用(指定环境)
// 适用于非 SeaVerse 平台或需要明确指定环境的应用
const client = new DataClient({
  appId: 'my-app-123',
  token: 'user-jwt-token',
  environment: 'production',    // 可选:'production' | 'staging' | 'development' | 'local'
});

// 方式3: 完全自定义(自定义 baseURL)
// 适用于私有部署或特殊环境
const client = new DataClient({
  appId: 'my-app-123',
  token: 'user-jwt-token',
  baseURL: 'https://custom-api.example.com', // 自定义API地址
});

配置选项说明:

| 参数 | 类型 | 必需 | 说明 | |-----|------|------|------| | appId | string | ✅ | 应用ID,从控制台获取 | | token | string | ✅ | 用户JWT token,用于身份验证 | | baseURL | string | ⬜️ | 自定义API地址,优先级最高 | | environment | Environment | ⬜️ | 环境类型,当未提供baseURL时使用 | | timeout | number | ⬜️ | 请求超时时间(毫秒),默认10000 | | headers | object | ⬜️ | 自定义请求头 | | debug | boolean | ⬜️ | 是否开启调试日志 |

2. 查询数据

// 查询列表
const notes = await client.query({
  table: 'notes',
  filters: {
    category: 'work',
    visibility: 'private',
  },
  order: {
    field: 'created_at',
    direction: 'desc',
  },
  pagination: {
    limit: 20,
    offset: 0,
  },
});

// 查询单条
const note = await client.get('note-id-123');

3. 创建数据

const newNote = await client.create({
  table: 'notes',
  data: {
    title: '我的笔记',
    content: '笔记内容...',
  },
  visibility: 'private',
  category: 'work',
  tags: ['important', 'todo'],
});

4. 更新数据

const updated = await client.update('note-id-123', {
  data: {
    title: '更新的标题',
    content: '更新的内容',
  },
  category: 'personal',
});

5. 删除数据

// 删除单条
await client.delete('note-id-123');

// 批量删除
await client.batchDelete(['id-1', 'id-2', 'id-3']);

6. 管理员操作

// 检查是否是管理员
const isAdmin = await client.isAdmin();

API 文档

API 概览

| 方法 | 说明 | 参数 | 返回值 | |------|------|------|--------| | query(options) | 查询数据列表 | QueryOptions | Promise<DataRecord[]> | | get(id) | 获取单条数据 | id: string | Promise<DataRecord \| null> | | create(options) | 创建数据 | CreateDataOptions | Promise<DataRecord> | | update(id, options) | 更新数据 | id: string, UpdateDataOptions | Promise<DataRecord> | | delete(id) | 删除数据 | id: string | Promise<void> | | batchDelete(ids) | 批量删除 | ids: string[] | Promise<void> | | queryWithPagination(options) | 查询带分页信息 | QueryOptions | Promise<PaginatedResponse<DataRecord>> | | isAdmin() | 检查管理员权限 | - | Promise<boolean> | | updateToken(token) | 更新JWT token | token: string | void | | updateAppId(appId) | 更新应用ID | appId: string | void | | getAppId() | 获取当前应用ID | - | string | | getUserId() | 获取当前用户ID | - | string |

查询选项(QueryOptions)

interface QueryOptions {
  // 表名(必填)
  table: string;

  // 过滤条件
  filters?: {
    id?: string;                // 数据 ID
    category?: string;          // 分类
    visibility?: 'public' | 'private'; // 可见性
    tags?: string[];            // 标签
    data?: Record<string, any>; // data_value 字段过滤
    created_after?: string;     // 创建时间(之后)
    created_before?: string;    // 创建时间(之前)
  };

  // 排序
  order?: {
    field: 'created_at' | 'updated_at';
    direction: 'asc' | 'desc';
  };

  // 分页
  pagination?: {
    limit: number;
    offset: number;
  };
}

数据记录(DataRecord)

interface DataRecord {
  id: string;
  app_id: string;
  table_name: string;
  data_value: Record<string, any>;  // 实际数据
  owner_user_id: string;
  visibility: 'public' | 'private';
  category?: string;
  tags?: string[];
  created_at: string;
  updated_at: string;
}

权限说明

RLS 自动控制

SDK 会自动通过 RLS 策略控制权限:

  • 应用隔离:用户只能访问自己应用的数据
  • 用户隔离:用户只能访问自己的私密数据
  • 公开数据:所有人可以读取公开数据
  • 管理员权限:管理员可以访问应用内所有数据

操作权限矩阵

| 操作 | Owner | Admin | 其他用户(private) | 其他用户(public) | |------|-------|-------|-------------------|-------------------| | 读取 | ✅ | ✅ | ❌ | ✅ | | 创建 | ✅ | ✅ | ✅(自己的) | ✅(自己的) | | 修改 | ✅ | ✅ | ❌ | ❌ | | 删除 | ✅ | ✅ | ❌ | ❌ |

错误处理

import { SDKError } from '@seaverse/data-sdk';

try {
  await client.create({ ... });
} catch (error) {
  if (error instanceof SDKError) {
    console.error('错误代码:', error.code);
    console.error('状态码:', error.statusCode);
    console.error('详情:', error.details);
  }
}

错误代码

  • REQUEST_FAILED - 请求失败
  • TIMEOUT - 请求超时
  • NETWORK_ERROR - 网络错误
  • INVALID_TOKEN - Token 无效
  • NOT_FOUND - 数据不存在或无权限
  • PERMISSION_DENIED - 权限不足
  • VALIDATION_ERROR - 参数验证失败

高级用法

动态更新 Token

// JWT 过期后更新 token
client.updateToken('new-jwt-token');

切换应用

// 切换到其他应用
client.updateAppId('another-app-id');

JSONB 字段查询

// 查询 data_value 中的字段
const results = await client.query({
  table: 'posts',
  filters: {
    data: {
      title: 'Hello World',  // data_value->>'title' = 'Hello World'
      author: 'Alice',        // data_value->>'author' = 'Alice'
    },
  },
});

标签查询

// 查询包含指定标签的数据
const results = await client.query({
  table: 'posts',
  filters: {
    tags: ['javascript', 'typescript'], // 包含任一标签
  },
});

时间范围查询

// 查询指定时间范围的数据
const results = await client.query({
  table: 'logs',
  filters: {
    created_after: '2026-01-01T00:00:00Z',
    created_before: '2026-01-31T23:59:59Z',
  },
});

分页查询

// 查询带总数的分页数据
const result = await client.queryWithPagination({
  table: 'posts',
  pagination: { limit: 10, offset: 0 },
});

console.log(`总共 ${result.total} 条,当前返回 ${result.data.length} 条`);
console.log(`是否还有更多: ${result.hasMore}`);

性能说明

基于新的 RLS 架构,SDK 具有以下性能特性:

  • 查询 10000 条数据:~30ms(vs 旧架构 50 秒)
  • STABLE 函数缓存:管理员查询自动缓存
  • 短路求值:优先检查 visibility 和 owner
  • 哈希分区:256 个分区,支持并行查询

环境配置

SDK 支持多环境部署,根据不同的使用场景灵活配置。

预设环境

| Environment | baseURL | 适用场景 | 自动检测规则 | |-------------|---------|----------|-------------| | production | https://data.seaverse.ai | 生产环境 | 默认环境 | | staging | https://data.sg.seaverse.dev | 预发布环境 | hostname 包含 staging | | development | https://data-dev.seaverse.dev | 开发测试 | hostname 包含 -dev.dev | | local | http://localhost:3000 | 本地开发 | hostname 是 localhost127.0.0.1 |

配置优先级

SDK 按以下优先级选择 API 端点:

  1. 显式 baseURL - 最高优先级,直接使用指定的URL
  2. environment 参数 - 使用预设环境配置
  3. 自动检测 - 最低优先级,根据 hostname 自动判断

使用示例

参见"快速开始 → 初始化 SDK"部分的三种初始化方式。

错误码说明

SDK 提供了详细的错误码,方便问题诊断:

| 错误码 | HTTP状态码 | 说明 | 解决方法 | |--------|-----------|------|---------| | REQUEST_FAILED | 4xx/5xx | 请求失败 | 检查请求参数和服务器状态 | | TIMEOUT | - | 请求超时 | 增加 timeout 配置或检查网络 | | NETWORK_ERROR | - | 网络错误 | 检查网络连接 | | INVALID_TOKEN | 401 | Token无效或过期 | 使用 updateToken() 更新token | | NOT_FOUND | 404 | 数据不存在或无权限 | 检查数据ID和权限 | | PERMISSION_DENIED | 403 | 权限不足 | 确认用户有相应权限 | | VALIDATION_ERROR | 400 | 参数验证失败 | 检查请求参数格式 |

版本历史

v0.1.0 (2026-01-10)

🎉 首个版本发布

  • ✅ 基于 PostgreSQL/AlloyDB + PostgREST + RLS 架构
  • ✅ 完整的 CRUD 操作支持
  • ✅ 多环境配置与自动检测
  • ✅ 分页查询支持
  • ✅ 管理员权限检查
  • ✅ TypeScript 类型定义
  • ✅ 完整的错误处理

相关资源

License

MIT © SeaVerse Team