import cookie, { CookieSerializeOptions } from "cookie"; import { createPluginObject } from "../type/PluginType"; type CookiePair = [string, string] | [string, string, CookieSerializeOptions]; class CookieJar { constructor() { const base = globalThis.window === globalThis ? document.cookie : ""; this.createJar("default", base); } /** 保存对应的 Cookie 字符串的 Map */ cookies = new Map(); /** 创建一个 Cookie 空间 */ createJar(tag: string, base: string) { const data = cookie.parse(base); this.cookies.set(tag, Object.entries(data)); } toString(tag = "default") { const jar = this.cookies.get(tag); if (jar) { return jar .map(([name, value, options]) => cookie.serialize(name, value, options) ) .join("; "); } return ""; } get(name: string, tag = "default") { const jar = this.cookies.get(tag); if (jar) { return jar.find((i) => i[0] === name); } return null; } set( name: string, value: string, options: CookieSerializeOptions = {}, tag = "default" ) { const jar = this.cookies.get(tag); if (jar) { const existedOne = jar.find((i) => i[0] === name); if (existedOne) { existedOne.splice(1, 2, value, options); } else { jar.push([name, value, options]); } return true; } return false; } remove(name: string, tag: "default") { const jar = this.cookies.get(tag); if (jar) { const index = jar.findIndex((i) => i[0] === name); if (index !== -1) { jar.splice(index, 1); } return true; } return false; } } /** 全局的 Cookie 管理 */ export const globalCookie = new CookieJar(); export const useCookie: createPluginObject<{ tag?: string; read?: boolean; write?: boolean; }> = ({ tag = "default", read = true, write = true } = {}) => ({ beforeRequest(data) { if (read) data.headers.set("cookie", globalCookie.toString(tag)); return data; }, afterRequest(data) { // 分发这次的 Cookie 到不同的域内 if (data.cookie && write) Object.entries(data.cookie as any).forEach(([name, value]) => { globalCookie.set(name, value as string, {}, tag); }); return data; }, });