From 09207e98f912b6d259495b7ae4861274d1604c81 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juhani=20Krekel=C3=A4?= Date: Sun, 19 May 2024 18:51:53 +0300 Subject: [PATCH] Tietokannan automaattinen tallentaminen ja lataaminen --- index.html | 7 ++----- käyttöliittymä.js | 1 + tietokanta.js | 43 ++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/index.html b/index.html index 9f4305e..9c56ee4 100644 --- a/index.html +++ b/index.html @@ -31,11 +31,8 @@ diff --git a/käyttöliittymä.js b/käyttöliittymä.js index 13e2c32..b460bce 100644 --- a/käyttöliittymä.js +++ b/käyttöliittymä.js @@ -19,6 +19,7 @@ function suorita([tietokanta, muutokset]) { for (const muutos of muutokset) { suoritaMuutos(tietokanta, muutos); } + tallennaTietokanta(tietokanta); } function suoritaMuutos(tietokanta, muutos) { diff --git a/tietokanta.js b/tietokanta.js index 588a315..23ea59d 100644 --- a/tietokanta.js +++ b/tietokanta.js @@ -73,6 +73,23 @@ class Tietokanta { historia = []; + static serialisoidusta(serialisoitu) { + const parsittu = JSON.parse(serialisoitu); + const tietokanta = new this; + tietokanta.seuraavaId = parsittu.seuraavaId; + const muutokset = []; + for (const taulu in parsittu.taulut) { + tietokanta.taulut.set(taulu, new Map); + for (let id in parsittu.taulut[taulu]) { + id = Number.parseInt(id); + const sisältö = parsittu.taulut[taulu][id]; + tietokanta.taulut.get(taulu).set(id, sisältö); + muutokset.push({taulu, id, uusi: sisältö}); + } + } + return [tietokanta, muutokset]; + } + constructor() { this.taulut.set(taulut.luokat, new Map); } @@ -154,6 +171,30 @@ class Tietokanta { }); return taulukko.map(([id, _]) => id); } + + serialisoi() { + return JSON.stringify(this, (avain, arvo) => { + if (avain === 'historia') { + return undefined; + } + if (arvo instanceof Map) { + return Object.fromEntries(arvo.entries()); + } + return arvo; + }); + } } -const _tietokanta = new Tietokanta; +function tallennaTietokanta(tietokanta) { + window.localStorage.setItem('tietokanta', tietokanta.serialisoi()); +} + +function lataaTietokanta() { + const serialisoitu = window.localStorage.getItem('tietokanta'); + if (serialisoitu === null) { + return; + } + let [tietokanta, muutokset] = Tietokanta.serialisoidusta(serialisoitu); + _tietokanta = tietokanta; + suorita([tietokanta, muutokset]); +}