userdo
Version:
A Durable Object base class that provides user authentication, per-user data storage, and real-time updates for Cloudflare Workers applications.
38 lines (37 loc) • 1.21 kB
JavaScript
import { GenericTable } from './table';
export class UserDODatabase {
constructor(storage, currentUserId, broadcast) {
this.storage = storage;
this.currentUserId = currentUserId;
this.broadcast = broadcast;
this.tables = new Map();
this.schemas = new Map();
}
table(name, schema, options = {}) {
if (!this.tables.has(name)) {
this.ensureTableExists(name, options);
const table = new GenericTable(name, schema, this.storage, this.currentUserId, this.broadcast);
this.tables.set(name, table);
this.schemas.set(name, schema);
}
return this.tables.get(name);
}
get raw() {
return this.storage.sql;
}
ensureTableExists(name, options) {
const createSQL = `CREATE TABLE IF NOT EXISTS "${name}" (
id TEXT PRIMARY KEY,
data TEXT NOT NULL,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
user_id TEXT${options.userScoped ? ' NOT NULL' : ''}
)`;
try {
this.storage.sql.exec(createSQL);
}
catch (err) {
console.log(`Table ${name} creation result:`, err);
}
}
}