import { R } from "utils/helper.js" import Router from "utils/router.js" class AuthController { constructor() {} /** * 通用请求函数:依次请求网址数组,返回第一个成功的响应及其类型 * @param {string[]} urls * @returns {Promise<{type: string, data: any}>} */ async 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") } async random(ctx) { const { type, data } = await this.fetchFirstSuccess(["https://api.miaomc.cn/image/get"]) if (type === "blob") { ctx.set("Content-Type", "image/jpeg") ctx.body = data } else { R.response(R.ERROR, "Failed to fetch image") } } /** * 路由注册 */ static createRoutes() { const controller = new AuthController() const router = new Router({ prefix: "/api/pics" }) router.get("/random", controller.random.bind(controller), { auth: false }) return router } } export default AuthController