Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export function setItem(key, value, options = {}) {
if (!key || !value) return false
const storageType = getStorageType(options)
const saveValue = JSON.stringify(value)
/* 1. Try localStorage */
if (useLocal(storageType)) {
// console.log('SET as localstorage', saveValue)
const oldValue = parse(localStorage.getItem(key))
localStorage.setItem(key, saveValue)
return { value, oldValue, location: LOCAL_STORAGE }
}
/* 2. Fallback to cookie */
if (useCookie(storageType)) {
// console.log('SET as cookie', saveValue)
const oldValue = parse(getCookie(key))
setCookie(key, saveValue)
return { value, oldValue, location: COOKIE }
}
/* 3. Fallback to window/global */
const oldValue = globalContext[key]
globalContext[key] = value
return { value, oldValue, location: GLOBAL }
}
export function getItem(key, options = {}) {
if (!key) return null
const storageType = getStorageType(options)
// Get value from all locations
if (storageType === 'all') return getAll(key)
/* 1. Try localStorage */
if (useLocal(storageType)) {
const value = localStorage.getItem(key)
if (value || storageType === LOCAL_STORAGE) return parse(value)
}
/* 2. Fallback to cookie */
if (useCookie(storageType)) {
const value = getCookie(key)
if (value || storageType === COOKIE) return parse(value)
}
/* 3. Fallback to window/global. */
return globalContext[key] || null
}
function getAll(key) {
return {
cookie: parse(getCookie(key)),
localStorage: parse(localStorage.getItem(key)),
global: globalContext[key] || null
}
}