UNIVPLMDataIntegration/GoView/src/utils/storage.ts

111 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-03-10 09:23:27 +08:00
import { JSONStringify, JSONParse } from './utils'
/**
* *
* @param k
* @param v stringiiy
* @returns RemovableRef
*/
export const setLocalStorage = <T>(k: string, v: T) => {
try {
window.localStorage.setItem(k, JSONStringify(v))
} catch (error) {
return false
}
}
/**
* *
* @param k
* @returns any
*/
export const getLocalStorage = (k: string) => {
const item = window.localStorage.getItem(k)
try {
return item ? JSONParse(item) : item
} catch (err) {
return item
}
}
/**
* *
* @param name
*/
export const clearLocalStorage = (name: string) => {
window.localStorage.removeItem(name)
}
/**
* *
* @param k
* @param v
* @returns RemovableRef
*/
export const setSessionStorage = <T>(k: string, v: T) => {
try {
window.sessionStorage.setItem(k, JSONStringify(v))
} catch (error) {
return false
}
}
/**
* *
* @returns any
*/
export const getSessionStorage: (k: string) => any = (k: string) => {
const item = window.sessionStorage.getItem(k)
try {
return item ? JSONParse(item) : item
} catch (err) {
return item
}
}
/**
* *
* @param name
*/
export const clearSessioStorage = (name: string) => {
window.sessionStorage.removeItem(name)
}
/**
* * cookie
* @param name
* @param cvalue
* @param exdays
*/
export const setCookie = (name: string, cvalue: string, exdays: number) => {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
const expires = "expires=" + d.toUTCString();
document.cookie = name + "=" + cvalue + "; " + expires;
}
/**
* * cookie
* @param cname
* @returns string
*/
export const getCookie = (cname: string) => {
const name = cname + "=";
const ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
}
return "";
}
/**
* * cookie
* @param name
* @returns string
*/
export const clearCookie = (name: string) => {
setCookie(name, "", -1);
}