improve persistent class

This commit is contained in:
Timo Hocker 2020-05-05 10:46:30 +02:00
parent ac79bf8ef7
commit ac3296387e
2 changed files with 47 additions and 30 deletions

46
lib/Persistent.ts Normal file
View File

@ -0,0 +1,46 @@
import { Assignable, Serializable } from './interfaces';
export abstract class Persistent implements Assignable, Serializable {
private _data: Record<string, unknown> = {};
private _properties: Record<string, string>;
public constructor (props: Record<string, string>) {
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<string, unknown>): 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<string, unknown> {
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];
}
}

View File

@ -1,34 +1,5 @@
export interface Assignable { export interface Assignable {
assign (a: Assignable): void; assign (a: Assignable): void;
assign_to (a: Assignable): void; assign_to (a: Assignable): void;
} to_object (): Record<string, unknown>;
export abstract class Persistent {
private data: Record<string, unknown> = {};
private properties: Record<string, string>;
public constructor() {
this.properties = this.define_properties();
}
public abstract define_properties(): Record<string, string>;
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<string, unknown>): void {
for (const key of Object.keys (obj))
this.data[key] = obj[key];
}
public get_data (): Record<string, unknown> {
return this.data;
}
wip
} }