/* * 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 , 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 = {}; protected readonly properties: Record = {}; 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): 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 { return copy_object (this._data) as Record; } 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]; } }