this repo has no description
at main 66 lines 2.6 kB view raw
1import { StoreBuilder, StoreUpdater } from "./builder.store" 2import type { ExtantKey, MigrationDef, MigrationFn, RowConstraint, SchemaConstraint, Simplify, StoreDef, UnusedKey, VersionDef } from "./schema" 3 4export class VersionBuilder<Schema extends SchemaConstraint> { 5 #stores: Map<string, StoreDef<string, any>> 6 #migrations: MigrationDef[] 7 8 constructor(previousStores: Map<string, StoreDef<string, any, any, any>> = new Map()) { 9 this.#stores = new Map(previousStores) 10 this.#migrations = [] 11 } 12 13 create<Name extends string>(name: UnusedKey<Name, Schema>) { 14 if (this.#stores.has(name)) 15 throw new Error(`cannot create store ${name} - already exists`) 16 17 return <Row extends RowConstraint> (callback: (b: StoreBuilder<Row>) => StoreBuilder<Row, any, any>) => { 18 const builder = callback(new StoreBuilder<Row>()) 19 const created = builder.build(name) 20 21 this.#stores.set(name, created) 22 this.#migrations.push(['create', name, created]) 23 24 return this as unknown as VersionBuilder<Simplify<Schema & {[K in Name]: Row}>> 25 } 26 } 27 28 update<Name extends string>(name: ExtantKey<Name, Schema>) { 29 const extant = this.#stores.get(name) 30 if (extant == null) throw new Error(`cannot update store ${name} - does not exist`) 31 32 return <NewRow extends RowConstraint = Schema[Name]> (callback: (u: StoreUpdater<Name, Schema[Name], any, any>) => StoreUpdater<Name, any, any, any>) => { 33 const updater = new StoreUpdater<Name, Schema[Name], typeof extant.__doc, typeof extant.__indexes>(extant as any) 34 const updated = callback(updater).build() 35 36 this.#stores.set(name, updated) 37 this.#migrations.push(['update', name, updated]) 38 39 return this as unknown as VersionBuilder<Simplify<Omit<Schema, Name> & {[K in Name]: NewRow}>> 40 } 41 } 42 43 drop<Name extends string>(name: Name): VersionBuilder<Omit<Schema, Name>> { 44 this.#stores.delete(name) 45 this.#migrations.push(['drop', name]) 46 47 return this as unknown as VersionBuilder<Simplify<Omit<Schema, Name>>> 48 } 49 50 migrate< 51 WriteOverrides extends SchemaConstraint, 52 OverriddenSchema extends SchemaConstraint = Simplify<Omit<Schema, keyof WriteOverrides> & WriteOverrides> 53 >(cb: MigrationFn<Schema, OverriddenSchema>): VersionBuilder<OverriddenSchema> { 54 this.#migrations.push(cb) 55 return this as unknown as VersionBuilder<OverriddenSchema> 56 } 57 58 build(): VersionDef<Simplify<Schema>> { 59 return { 60 stores: this.#stores, 61 migrations: this.#migrations, 62 63 __schema: undefined as unknown as Schema, 64 } 65 } 66}