@etsoo/shared
Version:
TypeScript shared utilities and functions
93 lines (92 loc) • 2.82 kB
JavaScript
import { NodeStorage } from "./node/Storage";
import { Utils } from "./Utils";
// Mock node
globalThis.localStorage ?? (globalThis.localStorage = new NodeStorage());
globalThis.sessionStorage ?? (globalThis.sessionStorage = new NodeStorage());
/**
* Storage utilities
* NodeStorage needs data persistance
*/
export var StorageUtils;
(function (StorageUtils) {
/**
* Set local storage data
* @param key Key name
* @param data Data, null for removal
*/
function setLocalData(key, data) {
if (data == null) {
localStorage.removeItem(key);
return;
}
localStorage.setItem(key, typeof data === "string" ? data : JSON.stringify(data));
}
StorageUtils.setLocalData = setLocalData;
/**
* Set session storage data
* @param key Key name
* @param data Data, null for removal
*/
function setSessionData(key, data) {
if (data == null) {
sessionStorage.removeItem(key);
return;
}
sessionStorage.setItem(key, typeof data === "string" ? data : JSON.stringify(data));
}
StorageUtils.setSessionData = setSessionData;
/**
* Get local storage data
* @param key Key name
* @param defaultValue Default value
*/
function getLocalData(key, defaultValue) {
// Get storage
const data = localStorage.getItem(key);
// No default value
if (defaultValue == null)
return Utils.parseString(data);
// Return
return Utils.parseString(data, defaultValue);
}
StorageUtils.getLocalData = getLocalData;
/**
* Get local storage object data
* @param key Key name
*/
function getLocalObject(key) {
// Get storage
const data = localStorage.getItem(key);
if (data == null)
return undefined;
return JSON.parse(data);
}
StorageUtils.getLocalObject = getLocalObject;
/**
* Get session storage data
* @param key Key name
* @param defaultValue Default value
*/
function getSessionData(key, defaultValue) {
// Get storage
const data = sessionStorage.getItem(key);
// No default value
if (defaultValue == null)
return Utils.parseString(data);
// Return
return Utils.parseString(data, defaultValue);
}
StorageUtils.getSessionData = getSessionData;
/**
* Get session storage object data
* @param key Key name
*/
function getSessionObject(key) {
// Get storage
const data = sessionStorage.getItem(key);
if (data == null)
return undefined;
return JSON.parse(data);
}
StorageUtils.getSessionObject = getSessionObject;
})(StorageUtils || (StorageUtils = {}));