2020-10-21 18:54:18 +00:00
|
|
|
import Dexie from 'dexie';
|
|
|
|
import {DatabaseService} from './database.service';
|
2020-10-22 02:12:04 +00:00
|
|
|
import {uuid_v4} from '../../utility';
|
2020-10-21 18:54:18 +00:00
|
|
|
|
|
|
|
export abstract class Model<InterfaceType> {
|
|
|
|
public static dbService?: DatabaseService;
|
|
|
|
|
|
|
|
public id?: number;
|
|
|
|
|
|
|
|
public static getSchema(): string {
|
|
|
|
throw new TypeError('Child class must implement.');
|
|
|
|
}
|
|
|
|
|
|
|
|
public static getTableName(): string {
|
|
|
|
throw new TypeError('Child class must implement.');
|
|
|
|
}
|
|
|
|
|
2020-10-22 02:12:04 +00:00
|
|
|
public static getUUID(): string {
|
|
|
|
return uuid_v4();
|
|
|
|
}
|
|
|
|
|
2020-10-21 18:54:18 +00:00
|
|
|
public abstract getDatabase(): Dexie.Table<InterfaceType, number>;
|
|
|
|
public abstract getSaveRecord(): any;
|
|
|
|
|
|
|
|
public staticClass() {
|
|
|
|
return (this.constructor as typeof Model);
|
|
|
|
}
|
|
|
|
|
|
|
|
public exists() {
|
|
|
|
return !!this.id;
|
|
|
|
}
|
|
|
|
|
|
|
|
public async save() {
|
2020-10-29 04:48:46 +00:00
|
|
|
const record = this.getSaveRecord();
|
|
|
|
|
|
|
|
for ( const prop in record ) {
|
|
|
|
if ( !record.hasOwnProperty(prop) ) {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if ( [true, false].includes(record[prop]) ) {
|
|
|
|
record[prop] = record[prop] ? 1 : 0;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-31 03:26:42 +00:00
|
|
|
record.offlineUpdatedAt = String(new Date());
|
|
|
|
|
2020-10-29 04:48:46 +00:00
|
|
|
this.id = await this.getDatabase().put(record);
|
2020-10-21 18:54:18 +00:00
|
|
|
}
|
|
|
|
}
|