c8ea5a3119
Replace fetch with wx/Taro.request in client-logging for WeChat mini program; point production build to api.dukanghaoke.com. Co-authored-by: Cursor <cursoragent@cursor.com>
55 lines
1.2 KiB
TypeScript
55 lines
1.2 KiB
TypeScript
const SESSION_KEY = 'dukang_session_id';
|
|
|
|
type WxStorage = {
|
|
getStorageSync?: (key: string) => unknown;
|
|
setStorageSync?: (key: string, value: unknown) => void;
|
|
};
|
|
|
|
function getWxStorage(): WxStorage | undefined {
|
|
return (globalThis as { wx?: WxStorage }).wx;
|
|
}
|
|
|
|
function readStorage(key: string): string | null {
|
|
if (typeof localStorage !== 'undefined') {
|
|
return localStorage.getItem(key);
|
|
}
|
|
try {
|
|
const v = getWxStorage()?.getStorageSync?.(key);
|
|
return v != null && v !== '' ? String(v) : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function writeStorage(key: string, value: string): void {
|
|
if (typeof localStorage !== 'undefined') {
|
|
localStorage.setItem(key, value);
|
|
return;
|
|
}
|
|
try {
|
|
getWxStorage()?.setStorageSync?.(key, value);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
}
|
|
|
|
function newSessionId(): string {
|
|
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
|
|
return crypto.randomUUID();
|
|
}
|
|
return `s_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
|
|
}
|
|
|
|
export function getSessionId(): string {
|
|
let id = readStorage(SESSION_KEY);
|
|
if (!id) {
|
|
id = newSessionId();
|
|
writeStorage(SESSION_KEY, id);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
export function touchSession(): string {
|
|
return getSessionId();
|
|
}
|