[ PROMPT_NODE_24082 ]
Do Storage 设计模式
[ SKILL_DOCUMENTATION ]
# DO 存储模式与最佳实践
## 模式迁移
typescript
export class MyDurableObject extends DurableObject {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
this.sql = ctx.storage.sql;
// 使用 SQLite 内置的 user_version pragma
const ver = this.sql.exec("PRAGMA user_version").one()?.user_version || 0;
if (ver === 0) {
this.sql.exec(`CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT)`);
this.sql.exec("PRAGMA user_version = 1");
}
if (ver === 1) {
this.sql.exec(`ALTER TABLE users ADD COLUMN email TEXT`);
this.sql.exec("PRAGMA user_version = 2");
}
}
}
## 内存缓存
typescript
export class UserCache extends DurableObject {
cache = new Map();
async getUser(id: string): Promise {
if (this.cache.has(id)) {
const cached = this.cache.get(id);
if (cached) return cached;
}
const user = await this.ctx.storage.get(`user:${id}`);
if (user) this.cache.set(id, user);
return user;
}
async updateUser(id: string, data: Partial) {
const updated = { ...await this.getUser(id), ...data };
this.cache.set(id, updated);
await this.ctx.storage.put(`user:${id}`, updated);
return updated;
}
}
## 速率限制
typescript
export class RateLimiter extends DurableObject {
async checkLimit(key: string, limit: number, window: number): Promise {
const now = Date.now();
this.sql.exec('DELETE FROM requests WHERE key = ? AND timestamp = limit) return false;
this.sql.exec('INSERT INTO requests (key, timestamp) VALUES (?, ?)', key, now);
return true;
}
}
## 使用闹钟进行批处理
typescript
export class BatchProcessor extends DurableObject {
pending: string[] = [];
async addItem(item: string) {
this.pending.push(item);
if (!await this.ctx.storage.getAlarm()) await this.ctx.storage.setAlarm(Date.now() + 5000);
}
async alarm() {
const items = [...this.pending];
this.pending = [];
this.sql.exec(`INSERT INTO processed_items (item, timestamp) VALUES ${items.map(() => "(?, ?)").join(", ")}`, ...items.flatMap(item => [item, Date.now()]));
}
}
## 初始化模式
typescript
export class Counter extends DurableObject {
value: number;