import { parseCookieHeader, serializeCookie } from "../src/compose/cookieUtils"; import app from "./app"; export function bootstrapServer() { async function fetchFirstSuccess(urls) { for (const url of urls) { try { const res = await fetch(url, { method: "get", mode: "cors", redirect: "follow", }); if (!res.ok) continue; const contentType = res.headers.get("content-type") || ""; let data, type; if (contentType.includes("application/json")) { data = await res.json(); type = "json"; } else if (contentType.includes("text/")) { data = await res.text(); type = "text"; } else { data = await res.blob(); type = "blob"; } return { type, data }; } catch (e) { // ignore and try next url } } throw new Error("All requests failed"); } app.use(async (ctx, next) => { const cookies = parseCookieHeader(ctx.request.headers.cookie as string); // 读取 const token = cookies["demo_2token"]; // 写入(HttpOnly 更安全) if (!token) { const setItem = serializeCookie("demo_2token", "from-mw", { httpOnly: true, path: "/", sameSite: "lax", }); ctx.set("Set-Cookie", [setItem]); } if (ctx.originalUrl !== "/api/pics/random") return await next(); const { type, data } = await fetchFirstSuccess([ "https://api.miaomc.cn/image/get", ]); if (type === "blob") { ctx.set("Content-Type", "image/jpeg"); // 下载 // ctx.set("Content-Disposition", "attachment; filename=random.jpg") ctx.body = data; } }); }