数通智联化工云平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.6 KiB

/**
* storage
* @param key key
* @param hour 使true
* @param expired undefined
*/
export const getStorage = (key: string, hour?: boolean, expired?: string) => {
let data: any
if (hour) {
data = window.localStorage.getItem(key)
try {
data = JSON.parse(data)
if (typeof data === 'object' && data.__value && data.__time) {
// 使用了时间的
// 在当前时间后,表示没过期
if (new Date().getTime() < data.__time) {
data = data.__value
} else {
// 过期了
data = expired || undefined
}
}
} catch (e) {
/* empty */
}
} else {
//保存时没传时间的,存在session里
data = window.sessionStorage.getItem(key)
}
try {
return JSON.parse(data)
} catch (e) {
return data
}
}
/** localStorage hour
* hour空时使用原始sessionStorage(key,value)
* hour=0使localStorage
* hour>0localStorage添加时间控制
* */
export function setStorage(key: string, data: any, hour?: number | null): void {
let newData = data
if (typeof data === 'object') {
newData = JSON.stringify(data)
}
if (hour === 0) {
window.localStorage.setItem(key, newData)
} else if (hour && hour > 0) {
const now = new Date()
const valueDate: string = JSON.stringify({
__value: data,
__time: now.setSeconds(now.getSeconds() + hour * 3600)
})
window.localStorage.setItem(key, valueDate)
} else {
window.sessionStorage.setItem(key, newData)
}
}