// utils/cookieManager.ts import { parse, serialize } from 'cookie' import type { SerializeOptions } from 'cookie' // Cookie选项类型 export interface CookieOptions extends Omit { expires?: Date maxAge?: number } // 通用Cookie管理器 export class CookieManager { // 环境检测 static isClient = typeof window !== 'undefined' static isServer = typeof window === 'undefined' // 设置Cookie static set(name: string, value: string, options: CookieOptions = {}): void { if (this.isClient) { document.cookie = serialize(name, value, { path: '/', sameSite: 'lax', ...options }) } } // 获取Cookie static get(name: string): string | undefined { if (this.isClient && document.cookie) { const cookies = parse(document.cookie) return cookies[name] } return undefined } // 删除Cookie static remove(name: string, options: CookieOptions = {}): void { this.set(name, '', { ...options, maxAge: 0, expires: new Date(0) }) } // 解析Cookie字符串 static parseCookies(cookieHeader: string | undefined): Record { if (!cookieHeader) return {} return parse(cookieHeader) } // 获取所有Cookie static getAll(): Record { if (this.isClient && document.cookie) { return parse(document.cookie) } return {} } // 批量设置Cookie static setMultiple(cookies: Record, options: CookieOptions = {}): void { Object.entries(cookies).forEach(([name, value]) => { this.set(name, value, options) }) } // 批量删除Cookie static removeMultiple(names: string[], options: CookieOptions = {}): void { names.forEach(name => { this.remove(name, options) }) } }