@mewters/smart-storage
Version:
A JavaScript/TypeScript library designed to simplify working with localStorage, sessionStorage, and cookies by offering automatic object conversion and consistent API.
46 lines (45 loc) • 1.52 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CookieStorage = void 0;
class CookieStorage {
static getCookieValue(name, cookieString) {
var _a;
const value = `; ${cookieString}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) {
return (_a = parts.pop()) === null || _a === void 0 ? void 0 : _a.split(';').shift();
}
}
static get(key, defaultValue) {
const value = this.getCookieValue(key, document.cookie);
if (value === null || value === undefined) {
return defaultValue;
}
try {
return JSON.parse(value);
}
catch (error) {
return value;
}
}
static set(key, value, days = 365) {
const d = new Date();
d.setTime(d.getTime() + days * 24 * 60 * 60 * 1000);
const expires = `expires=${d.toUTCString()}`;
const cookieValue = typeof value === 'string' ? value : JSON.stringify(value);
document.cookie = `${key}=${cookieValue};${expires};path=/`;
}
static remove(key) {
document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}
static removeItems(keys) {
keys.forEach(key => this.remove(key));
}
static clear() {
document.cookie.split(';').forEach(cookie => {
const key = cookie.split('=')[0];
this.remove(key);
});
}
}
exports.CookieStorage = CookieStorage;