modelling/lib/Persistent.ts
2020-05-17 17:01:32 +02:00

64 lines
1.9 KiB
TypeScript

/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of Modelling which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, May 2020
*/
import { copy_object } from '@sapphirecode/utilities';
import { Assignable, Serializable } from './interfaces';
type PersistentTypeString = 'string'|'number'|'boolean'|'array';
type PersistentPrimitive = string|number|boolean;
type PersistentType = PersistentPrimitive|PersistentPrimitive[];
export abstract class Persistent implements Assignable, Serializable {
private _data: Record<string, PersistentType> = {};
protected readonly properties: Record<string, PersistentTypeString> = {};
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] as PersistentType;
}
}
public to_object (): Record<string, PersistentType> {
return copy_object (this._data) as Record<string, PersistentType>;
}
public serialize (formatted = false): string {
if (formatted)
return JSON.stringify (this._data);
return JSON.stringify (this._data, null, 2);
}
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;
}
public set (key: string, value: unknown): void {
const prop = this.properties[key];
if (this.check_type (value, prop))
this._data[key] = value as PersistentType;
}
public get (key: string): PersistentType {
return this._data[key];
}
}