You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.0 KiB
TypeScript

1 month ago
// utils/cookieManager.ts
import { parse, serialize } from 'cookie'
import type { SerializeOptions } from 'cookie'
// Cookie选项类型
export interface CookieOptions extends Omit<SerializeOptions, 'expires'> {
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<string, string> {
if (!cookieHeader) return {}
return parse(cookieHeader)
}
// 获取所有Cookie
static getAll(): Record<string, string> {
if (this.isClient && document.cookie) {
return parse(document.cookie)
}
return {}
}
// 批量设置Cookie
static setMultiple(cookies: Record<string, string>, 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)
})
}
}