From ac3296387e51e1b6aff9a9f25a45ac77b9aac72f Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Tue, 5 May 2020 10:46:30 +0200 Subject: [PATCH] improve persistent class --- lib/Persistent.ts | 46 ++++++++++++++++++++++++++++++++++++ lib/interfaces/Assignable.ts | 31 +----------------------- 2 files changed, 47 insertions(+), 30 deletions(-) create mode 100644 lib/Persistent.ts diff --git a/lib/Persistent.ts b/lib/Persistent.ts new file mode 100644 index 0000000..0e429d7 --- /dev/null +++ b/lib/Persistent.ts @@ -0,0 +1,46 @@ +import { Assignable, Serializable } from './interfaces'; + +export abstract class Persistent implements Assignable, Serializable { + private _data: Record = {}; + private _properties: Record; + + public constructor (props: Record) { + this._properties = props; + } + + public assign (a: Assignable): void { + this.assign_object (a.to_object ()); + } + + public assign_to (a: Assignable): void { + a.assign (this); + } + + public assign_object (obj: Record): void { + for (const key of Object.keys (obj)) { + const prop = this._properties[key]; + if (typeof prop !== 'undefined' && typeof obj[key] === prop) + this._data[key] = obj[key]; + } + } + + public to_object (): Record { + return this._data; + } + + public serialize (formatted = false): string { + if (formatted) + return JSON.stringify (this.to_object ()); + return JSON.stringify (this.to_object (), null, 2); + } + + public set (key: string, value: unknown): void { + const prop = this._properties[key]; + if (typeof prop !== 'undefined' && typeof value === prop) + this._data[key] = value; + } + + public get (key: string): unknown { + return this._data[key]; + } +} diff --git a/lib/interfaces/Assignable.ts b/lib/interfaces/Assignable.ts index 5d22e9f..614d1b2 100644 --- a/lib/interfaces/Assignable.ts +++ b/lib/interfaces/Assignable.ts @@ -1,34 +1,5 @@ export interface Assignable { assign (a: Assignable): void; assign_to (a: Assignable): void; -} - -export abstract class Persistent { - private data: Record = {}; - private properties: Record; - - public constructor() { - this.properties = this.define_properties(); - } - - public abstract define_properties(): Record; - - public assign (da: Assignable): void { - this.assign_object (da.get_data ()); - } - - public assign_to (da: Assignable): void { - da.assign (this); - } - - public assign_object (obj: Record): void { - for (const key of Object.keys (obj)) - this.data[key] = obj[key]; - } - - public get_data (): Record { - return this.data; - } - - wip + to_object (): Record; }