blob: 6e67a5dfa58588038c6c43bd9cfa38f27ac5487d [file] [log] [blame]
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +02001import { Queue } from '@datastructures-js/queue';
2import StartupDataModel from '../../../models/StartupData';
3
4type StartupDataModification = (startupData: StartupDataModel) => void;
5
6export default class StartupDataStorage {
7 private startupData: StartupDataModel;
8 private modificationsQueue: Queue<StartupDataModification>;
9
10 constructor() {
11 const rawData = this.getHtmlElement().getAttribute('data-startup');
12 this.startupData = new StartupDataModel(rawData ? JSON.parse(rawData) : {});
13 this.modificationsQueue = new Queue();
14 }
15
16 get(): StartupDataModel {
17 return this.startupData;
18 }
19
20 enqueueModification(
21 modification: StartupDataModification,
22 ): StartupDataStorage {
23 this.modificationsQueue.enqueue(modification);
24 return this;
25 }
26
27 applyModifications(): StartupDataStorage {
28 while (!this.modificationsQueue.isEmpty()) {
29 const modification = this.modificationsQueue.dequeue();
30 modification(this.startupData);
31 }
32 this.persistToDOM();
33 return this;
34 }
35
36 private persistToDOM() {
37 const serializedData = JSON.stringify(this.startupData.data);
38 this.getHtmlElement().setAttribute('data-startup', serializedData);
39 }
40
41 private getHtmlElement() {
42 const htmlElement = document.querySelector('html');
43 if (!htmlElement) {
44 throw new Error("StartupDataStorage: couldn't find the html element.");
45 }
46 return htmlElement;
47 }
48}