modelling/lib/Persistent.ts

61 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-05-17 16:59:34 +02:00
/*
* 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
*/
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-06-06 15:48:43 +02:00
import { PersistentTypeString, PersistentType } from './Types';
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-17 17:01:32 +02:00
return copy_object (this._data) as Record<string, PersistentType>;
2020-05-05 10:46:30 +02:00
}
public serialize (formatted = false): string {
if (formatted)
2020-06-28 14:38:15 +02:00
return JSON.stringify (this._data, null, 2);
return JSON.stringify (this._data);
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];
}
}