spacetimedb-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SpacetimeDB Best Practices

SpacetimeDB 开发最佳实践

Comprehensive development guide for SpacetimeDB applications, covering both TypeScript server modules and client SDK integration with React. Contains rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
Package:
spacetimedb
(v1.4.0+)
这是一份针对SpacetimeDB应用的全面开发指南,涵盖TypeScript服务器模块开发以及客户端SDK与React的集成。指南包含8类规则,按影响优先级排序,可用于指导自动化重构与代码生成。
包依赖:
spacetimedb
(v1.4.0+)

When to Apply

适用场景

Reference these guidelines when:
  • Writing SpacetimeDB server modules in TypeScript
  • Designing table schemas and indexes
  • Implementing reducers for state mutations
  • Setting up client subscriptions and queries
  • Integrating SpacetimeDB with React applications
  • Optimizing real-time sync performance
在以下场景中可参考本指南:
  • 用TypeScript编写SpacetimeDB服务器模块时
  • 设计表结构与索引时
  • 实现用于状态变更的reducer时
  • 配置客户端订阅与查询时
  • 将SpacetimeDB与React应用集成时
  • 优化实时同步性能时

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Module DesignCRITICAL
module-
2Table Schema & IndexingCRITICAL
table-
3Reducer PatternsHIGH
reducer-
4Subscription OptimizationHIGH
subscription-
5Client State ManagementMEDIUM-HIGH
client-
6React IntegrationMEDIUM
react-
7TypeScript PatternsMEDIUM
ts-
8Real-time SyncLOW-MEDIUM
sync-
优先级类别影响程度前缀
1模块设计关键
module-
2表结构与索引关键
table-
3Reducer模式
reducer-
4订阅优化
subscription-
5客户端状态管理中高
client-
6React集成
react-
7TypeScript模式
ts-
8实时同步中低
sync-

Quick Reference

快速参考

Server Module API (TypeScript)

服务器模块API(TypeScript)

typescript
import { spacetimedb, table, t, ReducerContext } from 'spacetimedb';

// Define tables with the table builder
const Player = table(
  { name: 'player', public: true },
  {
    identity: t.identity().primaryKey(),
    name: t.string(),
    score: t.u64().index(),
    isOnline: t.bool().index(),
  }
);

// Define reducers
spacetimedb.reducer('create_player', { name: t.string() }, (ctx: ReducerContext, { name }) => {
  ctx.db.player.insert({
    identity: ctx.sender,
    name,
    score: 0n,
    isOnline: true,
  });
});

// Lifecycle hooks
spacetimedb.init((ctx: ReducerContext) => { /* module init */ });
spacetimedb.clientConnected((ctx: ReducerContext) => { /* client connected */ });
spacetimedb.clientDisconnected((ctx: ReducerContext) => { /* client disconnected */ });
typescript
import { spacetimedb, table, t, ReducerContext } from 'spacetimedb';

// Define tables with the table builder
const Player = table(
  { name: 'player', public: true },
  {
    identity: t.identity().primaryKey(),
    name: t.string(),
    score: t.u64().index(),
    isOnline: t.bool().index(),
  }
);

// Define reducers
spacetimedb.reducer('create_player', { name: t.string() }, (ctx: ReducerContext, { name }) => {
  ctx.db.player.insert({
    identity: ctx.sender,
    name,
    score: 0n,
    isOnline: true,
  });
});

// Lifecycle hooks
spacetimedb.init((ctx: ReducerContext) => { /* module init */ });
spacetimedb.clientConnected((ctx: ReducerContext) => { /* client connected */ });
spacetimedb.clientDisconnected((ctx: ReducerContext) => { /* client disconnected */ });

Client SDK API (TypeScript)

客户端SDK API(TypeScript)

typescript
import { DbConnection } from './generated';

// Build connection
const conn = DbConnection.builder()
  .withUri('ws://localhost:3000')
  .withModuleName('my-module')
  .onConnect((ctx, identity, token) => {
    // Setup subscriptions
    conn.subscription(['SELECT * FROM player WHERE isOnline = true']);
  })
  .onDisconnect((ctx, error) => { /* handle disconnect */ })
  .build();

// Call reducers
await conn.reducers.createPlayer('Alice');

// Access tables
const player = conn.db.player.identity.find(identity);
typescript
import { DbConnection } from './generated';

// Build connection
const conn = DbConnection.builder()
  .withUri('ws://localhost:3000')
  .withModuleName('my-module')
  .onConnect((ctx, identity, token) => {
    // Setup subscriptions
    conn.subscription(['SELECT * FROM player WHERE isOnline = true']);
  })
  .onDisconnect((ctx, error) => { /* handle disconnect */ })
  .build();

// Call reducers
await conn.reducers.createPlayer('Alice');

// Access tables
const player = conn.db.player.identity.find(identity);

React Integration

React集成

typescript
import { useTable, where, eq } from 'spacetimedb/react';
import { DbConnection, Player } from './generated';

function OnlinePlayers() {
  const { rows: players } = useTable<DbConnection, Player>(
    'player',
    where(eq('isOnline', true))
  );

  return players.map(p => <div key={p.identity.toHexString()}>{p.name}</div>);
}
typescript
import { useTable, where, eq } from 'spacetimedb/react';
import { DbConnection, Player } from './generated';

function OnlinePlayers() {
  const { rows: players } = useTable<DbConnection, Player>(
    'player',
    where(eq('isOnline', true))
  );

  return players.map(p => <div key={p.identity.toHexString()}>{p.name}</div>);
}

Rule Categories

规则类别

1. Module Design (CRITICAL)

1. 模块设计(关键)

  • module-single-responsibility
    - One module per domain concept
  • module-lifecycle
    - Use lifecycle hooks appropriately (init, clientConnected, clientDisconnected)
  • module-error-handling
    - Handle errors gracefully in module code
  • module-type-exports
    - Export types for client consumption
  • module-single-responsibility
    - 一个模块对应一个领域概念
  • module-lifecycle
    - 合理使用生命周期钩子(init、clientConnected、clientDisconnected)
  • module-error-handling
    - 在模块代码中优雅处理错误
  • module-type-exports
    - 导出供客户端使用的类型

2. Table Schema & Indexing (CRITICAL)

2. 表结构与索引(关键)

  • table-primary-keys
    - Choose appropriate primary key strategies
  • table-indexing
    - Add
    .index()
    for frequently queried columns
  • table-relationships
    - Model relationships between tables correctly
  • table-column-types
    - Use appropriate SpacetimeDB types
  • table-primary-keys
    - 选择合适的主键策略
  • table-indexing
    - 为频繁查询的字段添加
    .index()
  • table-relationships
    - 正确建模表之间的关联关系
  • table-column-types
    - 使用合适的SpacetimeDB类型

3. Reducer Patterns (HIGH)

3. Reducer模式(高)

  • reducer-atomicity
    - Keep reducers atomic and focused
  • reducer-validation
    - Validate inputs at reducer entry
  • reducer-authorization
    - Check caller identity for sensitive operations
  • reducer-batch-operations
    - Batch related mutations in single reducer
  • reducer-atomicity
    - 保持reducer的原子性与专注性
  • reducer-validation
    - 在reducer入口处验证输入参数
  • reducer-authorization
    - 对敏感操作检查调用者身份
  • reducer-batch-operations
    - 在单个reducer中批量处理相关变更

4. Subscription Optimization (HIGH)

4. 订阅优化(高)

  • subscription-selective
    - Subscribe only to needed data
  • subscription-filters
    - Use subscription filters to reduce data transfer
  • subscription-cleanup
    - Clean up subscriptions when no longer needed
  • subscription-batching
    - Batch subscription setup on client connect
  • subscription-selective
    - 仅订阅所需数据
  • subscription-filters
    - 使用订阅过滤器减少数据传输
  • subscription-cleanup
    - 不再需要时清理订阅
  • subscription-batching
    - 在客户端连接时批量配置订阅

5. Client State Management (MEDIUM-HIGH)

5. 客户端状态管理(中高)

  • client-connection-lifecycle
    - Handle connection/reconnection properly
  • client-optimistic-updates
    - Use optimistic updates for responsive UI
  • client-error-recovery
    - Handle reducer errors gracefully
  • client-identity
    - Manage identity tokens securely
  • client-connection-lifecycle
    - 正确处理连接/重连逻辑
  • client-optimistic-updates
    - 使用乐观更新实现响应式UI
  • client-error-recovery
    - 优雅处理reducer调用错误
  • client-identity
    - 安全管理身份令牌

6. React Integration (MEDIUM)

6. React集成(中)

  • react-use-subscription
    - Use subscription hooks correctly
  • react-table-hooks
    - Use
    useTable<DbConnection, Type>()
    for reactive data
  • react-reducer-hooks
    - Call
    conn.reducers.*
    with proper error handling
  • react-connection-status
    - Display connection status to users
  • react-use-subscription
    - 正确使用订阅钩子
  • react-table-hooks
    - 使用
    useTable<DbConnection, Type>()
    实现响应式数据
  • react-reducer-hooks
    - 调用
    conn.reducers.*
    时做好错误处理
  • react-connection-status
    - 向用户展示连接状态

7. TypeScript Patterns (MEDIUM)

7. TypeScript模式(中)

  • ts-generated-types
    - Use generated types from SpacetimeDB CLI
  • ts-strict-mode
    - Enable strict TypeScript for better type safety
  • ts-discriminated-unions
    - Use discriminated unions for state
  • ts-type-guards
    - Implement type guards for runtime validation
  • ts-generated-types
    - 使用SpacetimeDB CLI生成的类型
  • ts-strict-mode
    - 启用严格TypeScript模式以提升类型安全性
  • ts-discriminated-unions
    - 使用可区分联合类型管理状态
  • ts-type-guards
    - 实现类型保护用于运行时验证

8. Real-time Sync (LOW-MEDIUM)

8. 实时同步(中低)

  • sync-conflict-resolution
    - Handle concurrent modifications
  • sync-offline-support
    - Design for offline-first when needed
  • sync-debounce-updates
    - Debounce rapid UI updates
  • sync-presence
    - Implement user presence efficiently
  • sync-conflict-resolution
    - 处理并发修改冲突
  • sync-offline-support
    - 必要时按离线优先设计
  • sync-debounce-updates
    - 对频繁UI更新做防抖处理
  • sync-presence
    - 高效实现用户在线状态功能

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/module-single-responsibility.md
rules/table-primary-keys.md
rules/_sections.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
可查看单个规则文件获取详细说明与代码示例:
rules/module-single-responsibility.md
rules/table-primary-keys.md
rules/_sections.md
每个规则文件包含:
  • 规则重要性的简要说明
  • 错误代码示例及问题解析
  • 正确代码示例及解析
  • 额外背景信息与参考资料

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
包含所有规则详细内容的完整指南:
AGENTS.md