blob: 39e6b90024ef72e3cb4e723b3e8bb68eb746cfd3 [file] [log] [blame]
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +02001import { Queue } from '@datastructures-js/queue';
2import StartupDataModel from '../../../models/StartupData';
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +01003import {
4 StartupDataModification,
5 StartupDataStoragePort,
6} from '../../../services/communityConsole/StartupDataStorage.port';
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +02007
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +01008export default class StartupDataStorageAdapter
9 implements StartupDataStoragePort
10{
11 private isSetUp = false;
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +020012 private startupData: StartupDataModel;
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +010013 private modificationsQueue = new Queue<StartupDataModification>();
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +020014
15 get(): StartupDataModel {
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +010016 this.setUp();
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +020017 return this.startupData;
18 }
19
20 enqueueModification(
21 modification: StartupDataModification,
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +010022 ): StartupDataStorageAdapter {
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +020023 this.modificationsQueue.enqueue(modification);
24 return this;
25 }
26
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +010027 applyModifications(): StartupDataStorageAdapter {
28 this.setUp();
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +020029 while (!this.modificationsQueue.isEmpty()) {
30 const modification = this.modificationsQueue.dequeue();
31 modification(this.startupData);
32 }
33 this.persistToDOM();
34 return this;
35 }
36
Adrià Vilanova Martínezedbb73e2024-11-09 19:26:19 +010037 private setUp() {
38 if (this.isSetUp) return;
39
40 this.isSetUp = true;
41 const rawData = this.getHtmlElement().getAttribute('data-startup');
42 this.startupData = new StartupDataModel(rawData ? JSON.parse(rawData) : {});
43 }
44
Adrià Vilanova Martíneza2dda312024-05-18 00:35:51 +020045 private persistToDOM() {
46 const serializedData = JSON.stringify(this.startupData.data);
47 this.getHtmlElement().setAttribute('data-startup', serializedData);
48 }
49
50 private getHtmlElement() {
51 const htmlElement = document.querySelector('html');
52 if (!htmlElement) {
53 throw new Error("StartupDataStorage: couldn't find the html element.");
54 }
55 return htmlElement;
56 }
57}