import { Injectable } from '@angular/core'; import Dexie from 'dexie'; import {IMigration, Migration} from './Migration'; import {IMenuItem, MenuItem} from './MenuItem'; import {KeyValue, IKeyValue} from './KeyValue'; import {Codium, ICodium} from './Codium'; @Injectable({ providedIn: 'root' }) export class DatabaseService extends Dexie { protected static registeredModels = [Migration, MenuItem, KeyValue, Codium]; protected initialized = false; migrations!: Dexie.Table; menuItems!: Dexie.Table; keyValues!: Dexie.Table; codiums!: Dexie.Table; constructor( ) { super('NodedLocalDatabase'); } public async getKeyValue(key: string): Promise { const matches = await this.keyValues.where({ key }).toArray(); if ( matches.length > 0 ) { return matches[0] as KeyValue; } return new KeyValue(key, '', false); } public async createSchemata() { if ( this.initialized ) { return; } this.initialized = true; console.log('db', this); const staticClass = this.constructor as typeof DatabaseService; const schema: any = {}; for ( const ModelClass of staticClass.registeredModels ) { ModelClass.dbService = this; schema[ModelClass.getTableName()] = ModelClass.getSchema(); } await this.version(5).stores(schema); await this.open(); this.migrations = this.table('migrations'); this.migrations.mapToClass(Migration); this.menuItems = this.table('menuItems'); this.menuItems.mapToClass(MenuItem); this.keyValues = this.table('keyValues'); this.keyValues.mapToClass(KeyValue); this.codiums = this.table('codiums'); this.codiums.mapToClass(Codium); } }