46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
import { Assignable, Serializable } from './interfaces';
|
|
|
|
type PersistentTypeString = 'string'|'number'|'boolean';
|
|
type PersistentType = string|number|boolean;
|
|
|
|
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 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 as PersistentType;
|
|
}
|
|
|
|
public get (key: string): PersistentType {
|
|
return this._data[key];
|
|
}
|
|
}
|