UNPKG

userdo

Version:

A Durable Object base class for building applications on Cloudflare Workers.

42 lines (41 loc) 1.46 kB
import { GenericTable } from './table.js'; export class UserDODatabase { constructor(storage, currentUserId, broadcast) { this.storage = storage; this.currentUserId = currentUserId; this.broadcast = broadcast; this.tables = new Map(); this.schemas = new Map(); } setOrganizationContext(organizationId) { this.organizationContext = organizationId; } table(name, schema, options = {}) { if (!this.tables.has(name)) { this.ensureTableExists(name, options); const table = new GenericTable(name, schema, this.storage, this.currentUserId, () => options.organizationScoped ? this.organizationContext : undefined, 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' : ''}, organization_id TEXT${options.organizationScoped ? ' NOT NULL' : ''} )`; try { this.storage.sql.exec(createSQL); } catch (err) { console.log(`Table ${name} creation result:`, err); } } }