57 lines
1.6 KiB
TypeScript
57 lines
1.6 KiB
TypeScript
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);
|
|
}
|
|
|
|
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];
|
|
}
|
|
}
|