From 358fd60cf14ba5e0dbcb5a9e1d2db105fd7738f3 Mon Sep 17 00:00:00 2001 From: NDH Date: Sat, 23 Mar 2024 10:20:43 -0400 Subject: [PATCH] Update backup.js --- js/backup.js | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/js/backup.js b/js/backup.js index 5131b07..2248b55 100644 --- a/js/backup.js +++ b/js/backup.js @@ -1,41 +1,49 @@ import { restoreCache, todoCache } from './dbCache.js'; -/**NEW +/** * export data from persitence * @returns void - calls saveDataFile() */ export function backupData() { - // get all todo records + // get all todo records as a string const jsonData = JSON.stringify(Array.from(todoCache.entries())); + // create a dummy anchor element const link = document.createElement("a"); + // create the file blob from the data const file = new Blob([jsonData], { type: 'application/json' }); + // create a file url link.href = URL.createObjectURL(file); + // force the link to down load as file name 'backup.json' link.download = "backup.json"; + // stimulate the anchor click event link.click(); + // cleanup the url object (file) URL.revokeObjectURL(link.href); } /** * Restore data - * - * @export */ export function restoreData() { /** @type {HTMLElement | HTMLInputElement | null} */ const fileload = document.getElementById('fileload'); - const fileloadInput = /** @type {HTMLInputElement} */ (fileload) // type coersion + // inline type cast (coersion) + const fileloadInput = /** @type {HTMLInputElement} */ (fileload) + // simulate a user click event fileloadInput.click(); - fileloadInput.addEventListener('change', function () { - + // handle user action (file select) + fileloadInput.addEventListener('change', function () { /** @type {FileReader} */ const reader = new FileReader(); reader.onload = function () { - console.log('backup -> restoring') + // inline type cast restoreCache(/**@type{string}*/ (reader.result)); + // refresh the app to see the restored data window.location.reload(); }; - if( fileload && fileloadInput.files ) { + // read the first selected json file + if ( fileload && fileloadInput.files ) { reader.readAsText(fileloadInput.files[0]); } });