Skip to content

Commit

Permalink
Update backup.js
Browse files Browse the repository at this point in the history
  • Loading branch information
nhrones committed Mar 23, 2024
1 parent 9da2e1e commit 358fd60
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions js/backup.js
Original file line number Diff line number Diff line change
@@ -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]);
}
});
Expand Down

0 comments on commit 358fd60

Please sign in to comment.