open-vault/ui/app/lib/local-storage.js

48 lines
1.1 KiB
JavaScript
Raw Normal View History

/**
* Copyright (c) HashiCorp, Inc.
* SPDX-License-Identifier: MPL-2.0
*/
2018-04-03 14:16:57 +00:00
export default {
isLocalStorageSupported() {
try {
const key = `__storage__test`;
window.localStorage.setItem(key, null);
window.localStorage.removeItem(key);
return true;
} catch (e) {
// modify the e object so we can customize the error message.
// e.message is readOnly.
e.errors = [`This is likely due to your browser's cookie settings.`];
throw e;
}
},
2018-04-03 14:16:57 +00:00
getItem(key) {
const item = window.localStorage.getItem(key);
2018-04-03 14:16:57 +00:00
return item && JSON.parse(item);
},
setItem(key, val) {
window.localStorage.setItem(key, JSON.stringify(val));
2018-04-03 14:16:57 +00:00
},
removeItem(key) {
return window.localStorage.removeItem(key);
2018-04-03 14:16:57 +00:00
},
keys() {
return Object.keys(window.localStorage);
2018-04-03 14:16:57 +00:00
},
cleanupStorage(string, keyToKeep) {
if (!string) return;
const relevantKeys = this.keys().filter((str) => str.startsWith(string));
relevantKeys?.forEach((key) => {
if (key !== keyToKeep) {
localStorage.removeItem(key);
}
});
},
2018-04-03 14:16:57 +00:00
};