refactor: save object on restore (#842)

This commit is contained in:
Carlos Valente
2024-03-21 22:10:54 +01:00
committed by GitHub
parent a48be0f017
commit b06ab15190
+13 -11
View File
@@ -2,6 +2,7 @@ import { MaybeNumber, MaybeString, Playback } from 'ontime-types';
import { JSONFile } from 'lowdb/node'; import { JSONFile } from 'lowdb/node';
import { resolveRestoreFile } from '../setup/index.js'; import { resolveRestoreFile } from '../setup/index.js';
import { deepEqual } from 'fast-equals';
export type RestorePoint = { export type RestorePoint = {
playback: Playback; playback: Playback;
@@ -62,13 +63,13 @@ export function isRestorePoint(obj: unknown): obj is RestorePoint {
export class RestoreService { export class RestoreService {
private readonly filePath: MaybeString; private readonly filePath: MaybeString;
private readonly file: JSONFile<RestorePoint | null>; private readonly file: JSONFile<RestorePoint | null>;
private lastStore: MaybeString;
private failedCreateAttempts: number; private failedCreateAttempts: number;
private savedState: RestorePoint;
constructor(filePath: string) { constructor(filePath: string) {
this.filePath = filePath; this.filePath = filePath;
this.lastStore = null; this.savedState = null;
this.file = new JSONFile(this.filePath); this.file = new JSONFile(this.filePath);
this.failedCreateAttempts = 0; this.failedCreateAttempts = 0;
} }
@@ -100,15 +101,16 @@ export class RestoreService {
return; return;
} }
const stringifiedStore = JSON.stringify(newState); if (deepEqual(newState, this.savedState)) {
if (stringifiedStore !== this.lastStore) { return;
try { }
await this.write(newState);
this.lastStore = stringifiedStore; try {
this.failedCreateAttempts = 0; await this.write(newState);
} catch (_error) { this.savedState = { ...newState };
this.failedCreateAttempts += 1; this.failedCreateAttempts = 0;
} } catch (_error) {
this.failedCreateAttempts += 1;
} }
} }