modelling/lib/Persistent.ts

46 lines
1.3 KiB
TypeScript
Raw Normal View History

2020-05-05 10:46:30 +02:00
import { Assignable, Serializable } from './interfaces';
2020-05-07 18:59:27 +02:00
type PersistentTypeString = 'string'|'number'|'boolean';
type PersistentType = string|number|boolean;
2020-05-05 10:46:30 +02:00
export abstract class Persistent implements Assignable, Serializable {
2020-05-07 18:59:27 +02:00
private _data: Record<string, PersistentType> = {};
protected readonly properties: Record<string, PersistentTypeString> = {};
2020-05-05 11:37:48 +02:00
2020-05-05 10:46:30 +02:00
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)) {
2020-05-05 11:37:48 +02:00
const prop = this.properties[key];
2020-05-05 10:46:30 +02:00
if (typeof prop !== 'undefined' && typeof obj[key] === prop)
2020-05-07 18:59:27 +02:00
this._data[key] = obj[key] as PersistentType;
2020-05-05 10:46:30 +02:00
}
}
2020-05-07 18:59:27 +02:00
public to_object (): Record<string, PersistentType> {
2020-05-05 10:46:30 +02:00
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 {
2020-05-05 11:37:48 +02:00
const prop = this.properties[key];
2020-05-05 10:46:30 +02:00
if (typeof prop !== 'undefined' && typeof value === prop)
2020-05-07 18:59:27 +02:00
this._data[key] = value as PersistentType;
2020-05-05 10:46:30 +02:00
}
2020-05-07 18:59:27 +02:00
public get (key: string): PersistentType {
2020-05-05 10:46:30 +02:00
return this._data[key];
}
}