kawkab-frontend
Version:
Kawkab frontend is a frontend library for the Kawkab framework
101 lines (100 loc) • 2.38 kB
JavaScript
/**
* Checks if localStorage is available and usable.
* @returns {boolean} True if supported, false otherwise.
*/
function isSupported() {
try {
if (typeof window === 'undefined' || !window.localStorage) {
return false;
}
const testKey = '__test__';
window.localStorage.setItem(testKey, testKey);
window.localStorage.removeItem(testKey);
return true;
}
catch (e) {
return false;
}
}
/**
* Retrieves a value from localStorage and parses it as JSON.
* @param key The key to retrieve.
* @returns The stored value, or null if not found or on error.
*/
function get(key, defaultValue) {
if (!isSupported()) {
return null;
}
try {
const value = window.localStorage.getItem(key);
if (value === null) {
return defaultValue || null;
}
// Attempt to parse JSON, fall back to raw string if it fails
try {
return JSON.parse(value);
}
catch {
return value;
}
}
catch (error) {
console.error(`Error getting from localStorage: ${key}`, error);
return null;
}
}
/**
* Stores a value in localStorage after serializing it to JSON.
* @param key The key to store the value under.
* @param value The value to store (can be any JSON-serializable type).
*/
function set(key, value) {
if (!isSupported()) {
return;
}
try {
const stringValue = JSON.stringify(value);
window.localStorage.setItem(key, stringValue);
}
catch (error) {
console.error(`Error setting to localStorage: ${key}`, error);
}
}
/**
* Checks if a key exists in localStorage.
* @param key The key to check.
* @returns True if the key exists, false otherwise.
*/
function has(key) {
if (!isSupported()) {
return false;
}
return window.localStorage.getItem(key) !== null;
}
/**
* Removes an item from localStorage.
* @param key The key to remove.
*/
function remove(key) {
if (!isSupported()) {
return;
}
window.localStorage.removeItem(key);
}
/**
* Clears all items from localStorage.
*/
function clear() {
if (!isSupported()) {
return;
}
window.localStorage.clear();
}
export const LocalStorage = {
get,
set,
has,
remove,
clear,
isSupported,
};