关于 spacetimedb-typescript
spacetimedb-typescript 是用于构建 SpacetimeDB 模块类型安全 TypeScript 客户端的技能与参考资料,涵盖生成绑定、订阅同步数据、响应式更新及常见 API 陷阱。
主要功能
- 01生成 TypeScript 绑定
- 02连接 SpacetimeDB 模块
- 03订阅经 SQL 筛选的表数据
- 04处理实时表变更事件
- 05提供 React hooks 和 provider
- 06说明 API 陷阱与约束
适用场景
- 01构建使用 SpacetimeDB 数据的 TypeScript 应用
- 02保持客户端表状态同步
- 03创建响应式 React 界面
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ douglance/ spacetimedb --skill spacetimedb-typescript安装后在 Claude Code 中输入/spacetimedb-typescript确认已加载。
详细介绍
SpacetimeDB TypeScript SDK
构建可直接连接到 SpacetimeDB 模块的实时 TypeScript 客户端。SDK 为 Web 应用、Node.js、Deno、Bun 及其他 JavaScript 运行时提供类型安全的数据库访问、自动同步和响应式更新。
虚构的 API——切勿使用
这些 API 并不存在。LLM 经常会虚构它们。
// WRONG PACKAGE — does not exist
import { SpacetimeDBClient } from "@clockworklabs/spacetimedb-sdk";
// WRONG — these methods don't exist
SpacetimeDBClient.connect(...);
SpacetimeDBClient.call("reducer_name", [...]);
connection.call("reducer_name", [arg1, arg2]);
// WRONG — positional reducer arguments
conn.reducers.doSomething("value"); // WRONG!
正确模式:
// CORRECT IMPORTS
import { DbConnection, tables } from './module_bindings'; // Generated!
import { SpacetimeDBProvider, useTable, Identity } from 'spacetimedb/react';
// CORRECT REDUCER CALLS — object syntax, not positional!
conn.reducers.doSomething({ value: 'test' });
conn.reducers.updateItem({ itemId: 1n, newValue: 42 });
// CORRECT DATA ACCESS — useTable returns [rows, isLoading]
const [items, isLoading] = useTable(tables.item);
切勿:
- 虚构 Hook,例如
useItems()、useData()——使用useTable(tables.tableName) - 从虚假软件包导入——仅使用
spacetimedb、spacetimedb/react、./module_bindings
常见错误表
服务端错误
| 错误写法 | 正确写法 | 错误 |
|---|---|---|
缺少 package.json | 创建 package.json | "could not detect language" |
缺少 tsconfig.json | 创建 tsconfig.json | "TsconfigNotFound" |
入口文件不在 src/index.ts | 使用 src/index.ts | 模块无法打包 |
在 COLUMNS(第 2 个参数)中设置 indexes | 在 OPTIONS(第 1 个参数)中设置 indexes | "reading 'tag'" 错误 |
索引未指定 algorithm | algorithm: 'btree' | "reading 'tag'" 错误 |
filter({ ownerId }) | filter(ownerId) | "does not exist in type 'Range'" |
对唯一列使用 .filter() | 对唯一列使用 .find() | TypeError |
insert({ ...without id }) | insert({ id: 0n, ... }) | "Property 'id' is missing" |
const id = table.insert(...) | const row = table.insert(...) | .insert() 返回行,而非 ID |
.unique() + 显式索引 | 仅使用 .unique() | "name is used for multiple entities" |
| 从 index.ts 导入 spacetimedb | 从 schema.ts 导入 | "Cannot access before initialization" |
多列索引 .filter() | 使用单列索引 | PANIC 或静默返回空结果 |
在视图中使用 .iter() | 仅使用索引查找 | 视图无法扫描表 |
在过程函数中使用 ctx.db | ctx.withTx(tx => tx.db...) | 过程函数需要显式事务 |
在过程事务中使用 ctx.myTable | tx.db.myTable | 上下文变量错误 |
客户端错误
| 错误写法 | 正确写法 | 错误 |
|---|---|---|
@spacetimedb/sdk | spacetimedb | 404 / 子路径缺失 |
conn.reducers.foo("val") | conn.reducers.foo({ param: "val" }) | Reducer 语法错误 |
内联 connectionBuilder | useMemo(() => ..., []) | 每次渲染都会重新连接 |
const rows = useTable(table) | const [rows, isLoading] = useTable(table) | 元组解构 |
| 乐观 UI 更新 | 让订阅驱动状态 | 同步问题 |
<SpacetimeDBProvider builder={...}> | connectionBuilder={...} | Prop 名称错误 |
硬性要求
- 切勿编辑生成的绑定——使用
spacetime generate重新生成 - Reducers 是事务性的——不会返回数据
- Reducers 必须是确定性的——不能使用文件系统、网络、计时器或随机数
- 调用 Reducer 时使用对象语法——
{ param: 'value' },而非位置参数 - 从
./module_bindings导入DbConnection——不要从spacetimedb导入 - useTable 返回一个元组——
const [rows, isLoading] = useTable(tables.myTable) - 对 connectionBuilder 使用记忆化——用
useMemo(() => ..., [])包装,避免重新连接 - 视图只能使用索引查找——视图中不允许使用
.iter()
安装
npm install spacetimedb
# or
pnpm add spacetimedb
# or
yarn add spacetimedb
对于 Node.js 18-21,请安装 undici 对等依赖:
npm install spacetimedb undici
Node.js 22+ 和浏览器环境开箱即用。
生成类型绑定
使用 SDK 之前,请从 SpacetimeDB 模块生成 TypeScript 绑定:
spacetime generate --lang typescript --out-dir ./src/module_bindings --project-path ./server
这会创建一个 module_bindings 目录,其中包含:
index.ts——包括DbConnection、tables、reducers、query在内的主要导出- 每个表的类型定义(例如,
player_table.ts、user_table.ts) - 每个 Reducer 的类型定义(例如,
create_player_reducer.ts) - 自定义类型定义(例如,
point_type.ts)
基本连接设置
import { DbConnection } from './module_bindings';
const connection = DbConnection.builder()
.withUri('ws://localhost:3000')
.withModuleName('my_database')
.onConnect((conn, identity, token) => {
console.log('Connected with identity:', identity.toHexString());
// Store token for reconnection
localStorage.setItem('spacetimedb_token', token);
// Subscribe to tables after connection
conn.subscriptionBuilder().subscribe('SELECT * FROM player');
})
.onDisconnect((ctx) => {
console.log('Disconnected');
})
.onConnectError((ctx, error) => {
console.error('Connection error:', error);
})
.build();
Connection Builder 选项
DbConnection.builder()
// Required: SpacetimeDB server URI
.withUri('ws://localhost:3000')
// Required: Database module name or address
.withModuleName('my_database')
// Optional: Authentication token for reconnection
.withToken(localStorage.getItem('spacetimedb_token') ?? undefined)
// Optional: Enable compression (default: 'gzip')
.withCompression('gzip') // or 'none'
// Optional: Light mode reduces network traffic
.withLightMode(true)
// Optional: Wait for durable writes before receiving updates
.withConfirmedReads(true)
// Connection lifecycle callbacks
.onConnect((conn, identity, token) => { /* ... */ })
.onDisconnect((ctx, error) => { /* ... */ })
.onConnectError((ctx, error) => { /* ... */ })
.build();
订阅表
订阅会将表数据同步到客户端缓存。使用 SQL 查询筛选你接收的数据。
基本订阅
connection.subscriptionBuilder()
.onApplied((ctx) => {
console.log('Subscription applied, cache is ready');
})
.onError((ctx, error) => {
console.error('Subscription error:', error);
})
.subscribe('SELECT * FROM player');
多个查询
connection.subscriptionBuilder()
.subscribe([
'SELECT * FROM player',
'SELECT * FROM game_state',
'SELECT * FROM message WHERE room_id = 1'
]);
类型化查询构建器
使用生成的 query 对象进行类型安全的查询:
import { query } from './module_bindings';
// Simple query - selects all rows
connection.subscriptionBuilder()
.subscribe(query.player.build());
// Query with WHERE clause
connection.subscriptionBuilder()
.subscribe(
query.player
.where(row => row.name.eq('Alice'))
.build()
);
// Complex conditions
connection.subscriptionBuilder()
.subscribe(
query.player
.where(row => row.score.gte(100))
.where(row => row.isActive.eq(true))
.build()
);
订阅所有表
适用于开发或小型数据集:
connection.subscriptionBuilder().subscribeToAllTables();
取消订阅
const handle = connection.subscriptionBuilder()
.onApplied(() => console.log('Subscribed'))
.subscribe('SELECT * FROM player');
// Later, unsubscribe
handle.unsubscribe();
// Or with callback when complete
handle.unsubscribeThen((ctx) => {
console.log('Unsubscribed successfully');
});
访问表数据
订阅后,通过 connection.db 访问缓存的数据:
// Iterate all rows
for (const player of connection.db.player.iter()) {
console.log(player.name, player.score);
}
// Convert to array
const players = Array.from(connection.db.player.iter());
// Count rows
const count = connection.db.player.count();
// Find by primary key (if table has one)
const player = connection.db.player.id.find(42);
// Find by indexed column
const alice = connection.db.player.name.find('Alice');
表事件回调
监听表数据的实时变更:
// Row inserted
connection.db.player.onInsert((ctx, player) => {
console.log('New player:', player.name);
});
// Row deleted
connection.db.player.onDelete((ctx, player) => {
console.log('Player left:', player.name);
});
// Row updated (requires primary key on table)
connection.db.player.onUpdate((ctx, oldPlayer, newPlayer) => {
console.log(`${oldPlayer.name} score: ${oldPlayer.score} -> ${newPlayer.score}`);
});
// Remove callbacks
const onInsertCb = (ctx, player) => console.log(player);
connection.db.player.onInsert(onInsertCb);
connection.db.player.removeOnInsert(onInsertCb);
事件上下文
回调会收到一个 EventContext,其中包含事件相关信息:
connection.db.player.onInsert((ctx, player) => {
// Access to database
const allPlayers = Array.from(ctx.db.player.iter());
// Check event type
if (ctx.event.tag === 'Reducer') {
const { callerIdentity, reducer, status } = ctx.event.value;
console.log(`Triggered by reducer: ${reducer.name}`);
}
// Call other reducers
ctx.reducers.sendMessage({ playerId: player.id, text: 'Welcome!' });
});
调用 Reducer
Reducer 是用于修改数据库的服务端函数。重要:使用对象语法,而非位置参数。
// CORRECT: Object syntax
connection.reducers.createPlayer({ name: 'Alice', location: { x: 0, y: 0 } });
// WRONG: Positional arguments
// connection.reducers.createPlayer('Alice', { x: 0, y: 0 }); // DO NOT DO THIS
// Listen for reducer results
connection.reducers.onCreatePlayer((ctx, args) => {
const { callerIdentity, status, timestamp, energyConsumed } = ctx.event;
if (status.tag === 'Committed') {
console.log('Player created successfully');
} else if (status.tag === 'Failed') {
console.error('Failed:', status.value);
}
});
// Remove reducer callback
connection.reducers.removeOnCreatePlayer(callback);
从 snake_case 转换为 camelCase
- 服务端:
spacetimedb.reducer('do_something', ...) - 客户端:
conn.reducers.doSomething({ ... })
Reducer 标志
控制服务端如何处理 reducer 调用:
// NoSuccessNotify: Don't send TransactionUpdate on success (reduces traffic)
connection.setReducerFlags.movePlayer('NoSuccessNotify');
// FullUpdate: Always send full TransactionUpdate (default)
connection.setReducerFlags.movePlayer('FullUpdate');
视图
视图根据已连接的用户提供对私有表数据的筛选访问。
ViewContext 与 AnonymousViewContext
// ViewContext — has ctx.sender, result varies per user (computed per-subscriber)
spacetimedb.view({ name: 'my_items', public: true }, t.array(Item.rowType), (ctx) => {
return [...ctx.db.item.by_owner.filter(ctx.sender)];
});
// AnonymousViewContext — no ctx.sender, same result for everyone (shared, better perf)
spacetimedb.anonymousView({ name: 'leaderboard', public: true }, t.array(LeaderboardRow), (ctx) => {
return [...ctx.db.player.by_score.filter(/* top scores */)];
});
重要:视图只能使用索引查找
// WRONG — views cannot use .iter()
spacetimedb.view(
{ name: 'my_data_wrong', public: true },
t.array(PrivateData.rowType),
(ctx) => [...ctx.db.privateData.iter()] // NOT ALLOWED
);
// RIGHT — use index lookup
spacetimedb.view(
{ name: 'my_data', public: true },
t.array(PrivateData.rowType),
(ctx) => [...ctx.db.privateData.by_owner.filter(ctx.sender)]
);
订阅视图
视图需要显式订阅:
conn.subscriptionBuilder().subscribe([
'SELECT * FROM public_table',
'SELECT * FROM my_data', // Views need explicit SQL!
]);
Procedures(Beta 版)
Procedures 用于执行副作用(HTTP 请求等),这些操作是 reducer 无法完成的。
Procedures 目前处于 Beta 阶段。API 可能会变更。
定义 procedure
spacetimedb.procedure(
'fetch_external_data',
{ url: t.string() },
t.string(), // return type
(ctx, { url }) => {
const response = ctx.http.fetch(url);
return response.text();
}
);
重要:在 procedures 中访问数据库
Procedures 没有 ctx.db。使用 ctx.withTx() 访问数据库。
spacetimedb.procedure('save_fetched_data', { url: t.string() }, t.unit(), (ctx, { url }) => {
// Fetch external data (outside transaction)
const response = ctx.http.fetch(url);
const data = response.text();
// WRONG — ctx.db doesn't exist in procedures
// ctx.db.myTable.insert({ ... });
// RIGHT — use ctx.withTx() for database access
ctx.withTx(tx => {
tx.db.myTable.insert({
id: 0n,
content: data,
fetchedAt: tx.timestamp,
fetchedBy: tx.sender,
});
});
return {};
});
与 reducer 的主要区别
| Reducer | Procedure |
|---|---|
可直接使用 ctx.db | 必须使用 ctx.withTx(tx => tx.db...) |
| 自动事务 | 手动管理事务 |
| 不支持 HTTP/网络 | 可使用 ctx.http.fetch() |
| 不会向调用方返回值 | 可以向调用方返回数据 |
身份与身份验证
import { Identity } from 'spacetimedb';
// Get current identity
const identity = connection.identity;
console.log(identity?.toHexString());
// Compare identities
if (identity?.isEqual(otherIdentity)) {
console.log('Same user');
}
// Create from hex string
const parsed = Identity.fromString('0x1234...');
// Zero identity
const zero = Identity.zero();
// Compare identities using toHexString()
const isOwner = row.ownerId.toHexString() === myIdentity.toHexString();
持久化身份验证信息
// On connect, save the token
.onConnect((conn, identity, token) => {
localStorage.setItem('auth_token', token);
localStorage.setItem('identity', identity.toHexString());
})
// On reconnect, use saved token
.withToken(localStorage.getItem('auth_token') ?? undefined)
过期令牌处理
const onConnectError = (_ctx: ErrorContext, err: Error) => {
if (err.message?.includes('Unauthorized') || err.message?.includes('401')) {
localStorage.removeItem('auth_token');
window.location.reload();
}
};
React 集成
SDK 提供用于响应式 UI 更新的 React Hooks。
Provider 设置
import React, { useMemo } from 'react';
import ReactDOM from 'react-dom/client';
import { SpacetimeDBProvider } from 'spacetimedb/react';
import { DbConnection, query } from './module_bindings';
import App from './App';
function Root() {
// CRITICAL: Memoize to prevent reconnects on every render
const connectionBuilder = useMemo(() =>
DbConnection.builder()
.withUri('ws://localhost:3000')
.withModuleName('my_game')
.withToken(localStorage.getItem('auth_token') || undefined)
.onConnect((conn, identity, token) => {
console.log('Connected:', identity.toHexString());
localStorage.setItem('auth_token', token);
conn.subscriptionBuilder().subscribe(query.player.build());
})
.onDisconnect(() => console.log('Disconnected'))
.onConnectError((ctx, err) => console.error('Error:', err)),
[] // Empty deps - only create once
);
return (
<SpacetimeDBProvider connectionBuilder={connectionBuilder}>
<App />
</SpacetimeDBProvider>
);
}
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<Root />
</React.StrictMode>
);
useSpacetimeDB Hook
访问连接状态:
import { useSpacetimeDB } from 'spacetimedb/react';
function ConnectionStatus() {
const { isActive, identity, token, connectionId, connectionError } = useSpacetimeDB();
if (connectionError) {
return <div>Error: {connectionError.message}</div>;
}
if (!isActive) {
return <div>Connecting...</div>;
}
return <div>Connected as {identity?.toHexString()}</div>;
}
useTable Hook
订阅表数据并接收响应式更新。重要:返回一个元组 [rows, isLoading]。
import { useTable, where, eq } from 'spacetimedb/react';
import { tables } from './module_bindings';
function PlayerList() {
// CORRECT: Tuple destructuring
const [players, isLoading] = useTable(tables.player);
if (isLoading) return <div>Loading...</div>;
return (
<ul>
{players.map(player => (
<li key={player.id}>{player.name}: {player.score}</li>
))}
</ul>
);
}
function FilteredPlayerList() {
// Filtered players with callbacks
const [activePlayers, isLoading] = useTable(
tables.player,
where(eq('isActive', true)),
{
onInsert: (player) => console.log('Player joined:', player.name),
onDelete: (player) => console.log('Player left:', player.name),
onUpdate: (oldPlayer, newPlayer) => {
console.log(`${oldPlayer.name} updated`);
},
}
);
return (
<ul>
{activePlayers.map(player => (
<li key={player.id}>{player.name}</li>
))}
</ul>
);
}
useReducer Hook
从组件中调用 reducer:
import { useReducer } from 'spacetimedb/react';
import { reducers } from './module_bindings';
function CreatePlayerForm() {
const createPlayer = useReducer(reducers.createPlayer);
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
// CORRECT: Object syntax
createPlayer({ name, location: { x: 0, y: 0 } });
setName('');
};
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={e => setName(e.target.value)} />
<button type="submit">Create Player</button>
</form>
);
}
Vue 集成
SDK 提供 Vue 组合式函数:
import { SpacetimeDBProvider, useSpacetimeDB, useTable, useReducer } from 'spacetimedb/vue';
用法与 React Hooks 类似。
Svelte 集成
SDK 提供 Svelte Stores:
import { SpacetimeDBProvider, useSpacetimeDB, useTable, useReducer } from 'spacetimedb/svelte';
服务端用法(Node.js、Deno、Bun)
SDK 可在服务端 JavaScript 运行时中使用:
import { DbConnection } from './module_bindings';
async function main() {
const connection = DbConnection.builder()
.withUri('ws://localhost:3000')
.withModuleName('my_database')
.onConnect((conn, identity, token) => {
console.log('Connected:', identity.toHexString());
conn.subscriptionBuilder()
.onApplied(() => {
// Process data
for (const player of conn.db.player.iter()) {
console.log(player);
}
})
.subscribe('SELECT * FROM player');
})
.build();
}
main();
时间戳
服务端
import { Timestamp, ScheduleAt } from 'spacetimedb';
// Current time
ctx.db.item.insert({ id: 0n, createdAt: ctx.timestamp });
// Future time (add microseconds)
const future = ctx.timestamp.microsSinceUnixEpoch + 300_000_000n; // 5 minutes
客户端(重要)
时间戳是对象,而非数字:
// WRONG
const date = new Date(row.createdAt);
const date = new Date(Number(row.createdAt / 1000n));
// RIGHT
const date = new Date(Number(row.createdAt.microsSinceUnixEpoch / 1000n));
客户端上的 ScheduleAt
// ScheduleAt is a tagged union
if (scheduleAt.tag === 'Time') {
const date = new Date(Number(scheduleAt.value.microsSinceUnixEpoch / 1000n));
}
定时表
// Scheduled table MUST use scheduledId and scheduledAt columns
export const CleanupJob = table({
name: 'cleanup_job',
scheduled: 'run_cleanup' // reducer name
}, {
scheduledId: t.u64().primaryKey().autoInc(),
scheduledAt: t.scheduleAt(),
targetId: t.u64(), // Your custom data
});
// Scheduled reducer receives full row as arg
spacetimedb.reducer('run_cleanup', { arg: CleanupJob.rowType }, (ctx, { arg }) => {
// arg.scheduledId, arg.targetId available
// Row is auto-deleted after reducer completes
});
// Schedule a job
import { ScheduleAt } from 'spacetimedb';
const futureTime = ctx.timestamp.microsSinceUnixEpoch + 60_000_000n; // 60 seconds
ctx.db.cleanupJob.insert({
scheduledId: 0n,
scheduledAt: ScheduleAt.time(futureTime),
targetId: someId
});
// Cancel a job by deleting the row
ctx.db.cleanupJob.scheduledId.delete(jobId);
错误处理
连接错误
DbConnection.builder()
.onConnectError((ctx, error) => {
console.error('Failed to connect:', error.message);
// Implement retry logic
setTimeout(() => {
// Rebuild connection
}, 5000);
})
.build();
订阅错误
connection.subscriptionBuilder()
.onError((ctx, error) => {
console.error('Subscription failed:', error.message);
})
.subscribe('SELECT * FROM player');
Reducer 错误
connection.reducers.onCreatePlayer((ctx, args) => {
const { status } = ctx.event;
switch (status.tag) {
case 'Committed':
console.log('Success');
break;
case 'Failed':
console.error('Reducer failed:', status.value);
break;
case 'OutOfEnergy':
console.error('Out of energy');
break;
}
});
断开连接
// Gracefully disconnect
connection.disconnect();
类型参考
核心类型
import {
Identity, // User identity (256-bit)
ConnectionId, // Connection identifier
Timestamp, // SpacetimeDB timestamp
TimeDuration, // Duration type
Uuid, // UUID type
} from 'spacetimedb';
生成的类型
// From your module_bindings
import {
DbConnection, // Connection class
DbConnectionBuilder, // Builder class
SubscriptionBuilder, // Subscription builder
SubscriptionHandle, // Subscription handle
EventContext, // Event callback context
ReducerEventContext, // Reducer callback context
ErrorContext, // Error callback context
tables, // Table accessors for useTable
reducers, // Reducer definitions for useReducer
query, // Typed query builder
// Your custom types
Player,
Point,
// ... etc
} from './module_bindings';
命令
# Start local server
spacetime start
# Publish module
spacetime publish <module-name> --project-path <backend-dir>
# Clear database and republish
spacetime publish <module-name> --clear-database -y --project-path <backend-dir>
# Generate bindings
spacetime generate --lang typescript --out-dir <client>/src/module_bindings --project-path <backend-dir>
# View logs
spacetime logs <module-name>
最佳实践
-
存储身份验证令牌:保存
onConnect中的令牌,以便无缝重新连接。 -
连接后订阅:在
onConnect回调中设置订阅。 -
使用类型化查询:优先使用
query构建器,而不是原始 SQL 字符串,以确保类型安全。 -
处理所有连接状态:实现
onConnect、onDisconnect和onConnectError。 -
高频更新时使用轻量模式:为游戏或实时应用启用
.withLightMode(true)。 -
完成后取消订阅:组件卸载或不再需要数据时,清理订阅。
-
使用主键:在表上定义主键,以启用
onUpdate回调。 -
记忆化 connectionBuilder:始终使用
useMemo()包装,以避免重新连接。 -
让订阅驱动状态:避免乐观更新;让服务端作为事实来源。
常见模式
重连逻辑
function createConnection(token?: string) {
return DbConnection.builder()
.withUri('ws://localhost:3000')
.withModuleName('my_database')
.withToken(token)
.onConnect((conn, identity, newToken) => {
localStorage.setItem('token', newToken);
setupSubscriptions(conn);
})
.onDisconnect(() => {
// Reconnect after delay
setTimeout(() => {
createConnection(localStorage.getItem('token') ?? undefined);
}, 3000);
})
.build();
}
乐观更新
function PlayerScore({ player }) {
const updateScore = useReducer(reducers.updateScore);
const [optimisticScore, setOptimisticScore] = useState(player.score);
const handleClick = () => {
setOptimisticScore(prev => prev + 1);
updateScore({ playerId: player.id, delta: 1 });
};
// Sync with actual data
useEffect(() => {
setOptimisticScore(player.score);
}, [player.score]);
return <div onClick={handleClick}>Score: {optimisticScore}</div>;
}
使用多个条件进行筛选
// Using query builder
query.player
.where(row => row.team.eq('red'))
.where(row => row.score.gte(100))
.build();
// Using React hooks
const [redTeamHighScorers] = useTable(
tables.player,
where(eq('team', 'red')), // Additional filtering in client
);
const filtered = redTeamHighScorers.filter(p => p.score >= 100);
项目结构
服务端(backend/spacetimedb/)
src/schema.ts -> Tables, export spacetimedb
src/index.ts -> Reducers, lifecycle, import schema
package.json -> { "type": "module", "dependencies": { "spacetimedb": "^1.11.0" } }
tsconfig.json -> Standard config
避免循环导入
schema.ts -> defines tables AND exports spacetimedb
index.ts -> imports spacetimedb from ./schema, defines reducers
客户端(client/)
src/module_bindings/ -> Generated (spacetime generate)
src/main.tsx -> Provider, connection setup
src/App.tsx -> UI components
src/config.ts -> MODULE_NAME, SPACETIMEDB_URI