import { readErrorBody } from "../utils/fetch"; /** Modrinth API v2 的基础请求客户端,封装鉴权与 User-Agent。 */ export class ModrinthClient { private base = "https://api.modrinth.com/v2"; private token: string; private userAgent?: string; constructor(token: string, userAgent?: string) { this.token = token; this.userAgent = userAgent; } /** 构造通用请求头(Authorization,以及可选的 User-Agent)。 */ private headers(): Record { const h: Record = { Authorization: this.token, }; if (this.userAgent) { h["User-Agent"] = this.userAgent; } return h; } /** 发送 GET 请求并解析 JSON 响应体。 */ async get(path: string): Promise { const res = await fetch(`${this.base}${path}`, { headers: this.headers(), }); if (!res.ok) { const body = await readErrorBody(res); throw new Error( `Modrinth API GET ${path} failed: ${res.status} ${res.statusText}\n${body}`, ); } return res.json() as Promise; } /** * 发送 POST 请求,body 为 FormData(multipart/form-data)。 * 不手动设置 Content-Type,让 fetch 自动生成含 boundary 的头。 */ async post(path: string, body: FormData): Promise { const res = await fetch(`${this.base}${path}`, { method: "POST", headers: this.headers(), body, }); if (!res.ok) { const resBody = await readErrorBody(res); throw new Error( `Modrinth API POST ${path} failed: ${res.status} ${res.statusText}\n${resBody}`, ); } return res.json() as Promise; } }