/** * Local database using provided records to store the data. * * @license * Copyright 2022 Marco Fucci di Napoli (mfucci@gmail.com) * SPDX-License-Identifier: Apache-2.0 */ import { Record } from "./Record"; import { Database } from "./Database"; import EventEmitter from "events"; interface InternalRecordMap { "update": T | undefined; } export declare interface InternalRecord { on>(event: K, listener: (value: InternalRecordMap[K]) => void): this; once>(event: K, listener: (value: InternalRecordMap[K]) => void): this; emit>(event: K, value: InternalRecordMap[K]): boolean; } export class InternalRecord extends EventEmitter { private value: T; constructor(value: T) { super(); this.value = value; } get(): T { return this.value; } set(value: T) { this.value = value; this.emit("update", value); } } export class RecordDatabase extends Database { private readonly internalRecords = new Map>(); constructor() { super(); } async getRecord(key: string): Promise> { return this.createRecord(key); } protected getInternal(record: Record): T | undefined { const internalRecord = this.internalRecords.get(record.key); return internalRecord?.get(); } protected async setInternal(record: Record, value?: T) { const internalRecord = this.internalRecords.get(record.key); internalRecord?.set(value); return internalRecord?.get(); } setInternalRecord(key: string, record: InternalRecord) { const previousRecord = this.internalRecords.get(key); if (previousRecord !== undefined) { previousRecord.removeAllListeners("update"); } this.internalRecords.set(key, record); record.on("update", value => this.emitUpdate(key, value)); this.emitUpdate(key, record.get()); } getInternalRecord(key: string) { return this.internalRecords.get(key); } }