spacetimedb-best-practices
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSpacetimeDB 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: (v1.4.0+)
spacetimedb这是一份针对SpacetimeDB应用的全面开发指南,涵盖TypeScript服务器模块开发以及客户端SDK与React的集成。指南包含8类规则,按影响优先级排序,可用于指导自动化重构与代码生成。
包依赖: (v1.4.0+)
spacetimedbWhen 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
按优先级划分的规则类别
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Module Design | CRITICAL | |
| 2 | Table Schema & Indexing | CRITICAL | |
| 3 | Reducer Patterns | HIGH | |
| 4 | Subscription Optimization | HIGH | |
| 5 | Client State Management | MEDIUM-HIGH | |
| 6 | React Integration | MEDIUM | |
| 7 | TypeScript Patterns | MEDIUM | |
| 8 | Real-time Sync | LOW-MEDIUM | |
| 优先级 | 类别 | 影响程度 | 前缀 |
|---|---|---|---|
| 1 | 模块设计 | 关键 | |
| 2 | 表结构与索引 | 关键 | |
| 3 | Reducer模式 | 高 | |
| 4 | 订阅优化 | 高 | |
| 5 | 客户端状态管理 | 中高 | |
| 6 | React集成 | 中 | |
| 7 | TypeScript模式 | 中 | |
| 8 | 实时同步 | 中低 | |
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. 模块设计(关键)
- - One module per domain concept
module-single-responsibility - - Use lifecycle hooks appropriately (init, clientConnected, clientDisconnected)
module-lifecycle - - Handle errors gracefully in module code
module-error-handling - - Export types for client consumption
module-type-exports
- - 一个模块对应一个领域概念
module-single-responsibility - - 合理使用生命周期钩子(init、clientConnected、clientDisconnected)
module-lifecycle - - 在模块代码中优雅处理错误
module-error-handling - - 导出供客户端使用的类型
module-type-exports
2. Table Schema & Indexing (CRITICAL)
2. 表结构与索引(关键)
- - Choose appropriate primary key strategies
table-primary-keys - - Add
table-indexingfor frequently queried columns.index() - - Model relationships between tables correctly
table-relationships - - Use appropriate SpacetimeDB types
table-column-types
- - 选择合适的主键策略
table-primary-keys - - 为频繁查询的字段添加
table-indexing.index() - - 正确建模表之间的关联关系
table-relationships - - 使用合适的SpacetimeDB类型
table-column-types
3. Reducer Patterns (HIGH)
3. Reducer模式(高)
- - Keep reducers atomic and focused
reducer-atomicity - - Validate inputs at reducer entry
reducer-validation - - Check caller identity for sensitive operations
reducer-authorization - - Batch related mutations in single reducer
reducer-batch-operations
- - 保持reducer的原子性与专注性
reducer-atomicity - - 在reducer入口处验证输入参数
reducer-validation - - 对敏感操作检查调用者身份
reducer-authorization - - 在单个reducer中批量处理相关变更
reducer-batch-operations
4. Subscription Optimization (HIGH)
4. 订阅优化(高)
- - Subscribe only to needed data
subscription-selective - - Use subscription filters to reduce data transfer
subscription-filters - - Clean up subscriptions when no longer needed
subscription-cleanup - - Batch subscription setup on client connect
subscription-batching
- - 仅订阅所需数据
subscription-selective - - 使用订阅过滤器减少数据传输
subscription-filters - - 不再需要时清理订阅
subscription-cleanup - - 在客户端连接时批量配置订阅
subscription-batching
5. Client State Management (MEDIUM-HIGH)
5. 客户端状态管理(中高)
- - Handle connection/reconnection properly
client-connection-lifecycle - - Use optimistic updates for responsive UI
client-optimistic-updates - - Handle reducer errors gracefully
client-error-recovery - - Manage identity tokens securely
client-identity
- - 正确处理连接/重连逻辑
client-connection-lifecycle - - 使用乐观更新实现响应式UI
client-optimistic-updates - - 优雅处理reducer调用错误
client-error-recovery - - 安全管理身份令牌
client-identity
6. React Integration (MEDIUM)
6. React集成(中)
- - Use subscription hooks correctly
react-use-subscription - - Use
react-table-hooksfor reactive datauseTable<DbConnection, Type>() - - Call
react-reducer-hookswith proper error handlingconn.reducers.* - - Display connection status to users
react-connection-status
- - 正确使用订阅钩子
react-use-subscription - - 使用
react-table-hooks实现响应式数据useTable<DbConnection, Type>() - - 调用
react-reducer-hooks时做好错误处理conn.reducers.* - - 向用户展示连接状态
react-connection-status
7. TypeScript Patterns (MEDIUM)
7. TypeScript模式(中)
- - Use generated types from SpacetimeDB CLI
ts-generated-types - - Enable strict TypeScript for better type safety
ts-strict-mode - - Use discriminated unions for state
ts-discriminated-unions - - Implement type guards for runtime validation
ts-type-guards
- - 使用SpacetimeDB CLI生成的类型
ts-generated-types - - 启用严格TypeScript模式以提升类型安全性
ts-strict-mode - - 使用可区分联合类型管理状态
ts-discriminated-unions - - 实现类型保护用于运行时验证
ts-type-guards
8. Real-time Sync (LOW-MEDIUM)
8. 实时同步(中低)
- - Handle concurrent modifications
sync-conflict-resolution - - Design for offline-first when needed
sync-offline-support - - Debounce rapid UI updates
sync-debounce-updates - - Implement user presence efficiently
sync-presence
- - 处理并发修改冲突
sync-conflict-resolution - - 必要时按离线优先设计
sync-offline-support - - 对频繁UI更新做防抖处理
sync-debounce-updates - - 高效实现用户在线状态功能
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.mdEach 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