|
| 1 | +import {Loki} from "../../loki/src/loki"; |
| 2 | + |
| 3 | +function localStorageAvailable() { |
| 4 | + try { |
| 5 | + return (window && window.localStorage !== undefined && window.localStorage !== null); |
| 6 | + } catch (e) { |
| 7 | + return false; |
| 8 | + } |
| 9 | +} |
| 10 | + |
| 11 | +/** |
| 12 | + * A loki persistence adapter which persists to web browser's local storage object |
| 13 | + * @constructor LokiLocalStorageAdapter |
| 14 | + */ |
| 15 | +export class LokiLocalStorage { |
| 16 | + /** |
| 17 | + * loadDatabase() - Load data from localstorage |
| 18 | + * @param {string} dbname - the name of the database to load |
| 19 | + * @returns {Promise} a Promise that resolves after the database was loaded |
| 20 | + * @memberof LokiLocalStorageAdapter |
| 21 | + */ |
| 22 | + loadDatabase(dbname) { |
| 23 | + if (localStorageAvailable()) { |
| 24 | + return Promise.resolve(localStorage.getItem(dbname)); |
| 25 | + } |
| 26 | + |
| 27 | + return Promise.reject(new Error("localStorage is not available")); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * saveDatabase() - save data to localstorage, will throw an error if the file can't be saved |
| 32 | + * might want to expand this to avoid dataloss on partial save |
| 33 | + * @param {string} dbname - the filename of the database to load |
| 34 | + * @returns {Promise} a Promise that resolves after the database was saved |
| 35 | + * @memberof LokiLocalStorageAdapter |
| 36 | + */ |
| 37 | + saveDatabase(dbname, dbstring) { |
| 38 | + if (localStorageAvailable()) { |
| 39 | + localStorage.setItem(dbname, dbstring); |
| 40 | + |
| 41 | + return Promise.resolve(); |
| 42 | + } |
| 43 | + |
| 44 | + return Promise.reject(new Error("localStorage is not available")); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * deleteDatabase() - delete the database from localstorage, will throw an error if it |
| 49 | + * can't be deleted |
| 50 | + * @param {string} dbname - the filename of the database to delete |
| 51 | + * @returns {Promise} a Promise that resolves after the database was deleted |
| 52 | + * @memberof LokiLocalStorageAdapter |
| 53 | + */ |
| 54 | + deleteDatabase(dbname) { |
| 55 | + if (localStorageAvailable()) { |
| 56 | + localStorage.removeItem(dbname); |
| 57 | + |
| 58 | + return Promise.resolve(); |
| 59 | + } |
| 60 | + |
| 61 | + return Promise.reject(new Error("localStorage is not available")); |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +Loki.LokiLocalStorage = LokiLocalStorage; |
| 66 | + |
| 67 | +export default LokiLocalStorage; |
0 commit comments