modelling/lib/Persistent.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-05-09 18:06:13 +02:00
import { copy_object } from '@sapphirecode/utilities';
2020-05-05 10:46:30 +02:00
import { Assignable, Serializable } from './interfaces';
2020-05-09 18:06:13 +02:00
type PersistentTypeString = 'string'|'number'|'boolean'|'array';
type PersistentPrimitive = string|number|boolean;
type PersistentType = PersistentPrimitive|PersistentPrimitive[];
2020-05-07 18:59:27 +02:00
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-09 18:06:13 +02:00
return copy_object (this._data);
2020-05-05 10:46:30 +02:00
}
public serialize (formatted = false): string {
if (formatted)
2020-05-13 11:51:26 +02:00
return JSON.stringify (this._data);
return JSON.stringify (this._data, null, 2);
2020-05-05 10:46:30 +02:00
}
2020-05-09 18:06:13 +02:00
private check_type (value: unknown, prop: PersistentTypeString): boolean {
if (typeof prop === 'undefined')
return false;
if (prop === 'array')
return Array.isArray (value);
return typeof value === prop;
}
2020-05-05 10:46:30 +02:00
public set (key: string, value: unknown): void {
2020-05-05 11:37:48 +02:00
const prop = this.properties[key];
2020-05-09 18:06:13 +02:00
if (this.check_type (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];
}
}