177 行
5.7 KiB
TypeScript
177 行
5.7 KiB
TypeScript
import { API_BASE } from "./endpoints"
|
||
import type { ApiResponse } from "../types/api"
|
||
|
||
export type ApiTransport = "plugin-bridge" | "direct-fetch"
|
||
|
||
export class ApiClientError extends Error {
|
||
readonly code: string
|
||
readonly details: Record<string, unknown>
|
||
|
||
constructor(code: string, message: string, details: Record<string, unknown> = {}) {
|
||
super(message)
|
||
this.name = "ApiClientError"
|
||
this.code = code
|
||
this.details = details
|
||
}
|
||
}
|
||
|
||
export async function getJson<T>(endpoint: string, query?: Record<string, string | number | boolean | undefined>) {
|
||
return request<T>(endpoint, { method: "GET", query })
|
||
}
|
||
|
||
export async function postJson<T>(endpoint: string, body?: unknown) {
|
||
return request<T>(endpoint, { method: "POST", body })
|
||
}
|
||
|
||
export async function putJson<T>(endpoint: string, body?: unknown) {
|
||
return request<T>(endpoint, { method: "PUT", body })
|
||
}
|
||
|
||
export function getApiTransport(): ApiTransport {
|
||
const bridge = typeof window === "undefined" ? undefined : window.AstrBotPluginPage
|
||
return bridge && (typeof bridge.apiGet === "function" || typeof bridge.apiPost === "function")
|
||
? "plugin-bridge"
|
||
: "direct-fetch"
|
||
}
|
||
|
||
export async function request<T>(
|
||
endpoint: string,
|
||
options: {
|
||
method?: "GET" | "POST" | "PUT" | "DELETE"
|
||
query?: Record<string, string | number | boolean | undefined>
|
||
body?: unknown
|
||
} = {},
|
||
): Promise<T> {
|
||
const bridgePayload = await requestViaPluginBridge<T>(endpoint, options)
|
||
if (bridgePayload !== undefined) {
|
||
return unwrapApiResponse(bridgePayload)
|
||
}
|
||
|
||
const url = buildUrl(endpoint, options.query)
|
||
let response: Response
|
||
try {
|
||
response = await fetch(url, {
|
||
method: options.method ?? "GET",
|
||
headers: options.body === undefined ? undefined : { "Content-Type": "application/json" },
|
||
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||
})
|
||
} catch (err) {
|
||
throw new ApiClientError("network_unreachable", "无法连接 ImageStudio 后端接口", {
|
||
endpoint,
|
||
transport: "direct-fetch",
|
||
url,
|
||
reason: err instanceof Error ? err.message : String(err),
|
||
})
|
||
}
|
||
|
||
const payload = await parseResponsePayload<T>(response, endpoint, url)
|
||
if (!response.ok && !isApiResponse<T>(payload)) {
|
||
throw new ApiClientError("http_error", `接口请求失败(HTTP ${response.status})`, {
|
||
endpoint,
|
||
transport: "direct-fetch",
|
||
url,
|
||
status: response.status,
|
||
status_text: response.statusText,
|
||
})
|
||
}
|
||
return unwrapApiResponse(payload)
|
||
}
|
||
|
||
async function requestViaPluginBridge<T>(
|
||
endpoint: string,
|
||
options: {
|
||
method?: "GET" | "POST" | "PUT" | "DELETE"
|
||
query?: Record<string, string | number | boolean | undefined>
|
||
body?: unknown
|
||
},
|
||
): Promise<T | ApiResponse<T> | undefined> {
|
||
const bridge = window.AstrBotPluginPage
|
||
if (!bridge) {
|
||
return undefined
|
||
}
|
||
const method = options.method ?? "GET"
|
||
if (typeof bridge.ready === "function") {
|
||
await bridge.ready()
|
||
}
|
||
if (method === "GET" && typeof bridge.apiGet === "function") {
|
||
return bridge.apiGet<T | ApiResponse<T>>(endpoint, compactQuery(options.query))
|
||
}
|
||
if (method === "POST" && typeof bridge.apiPost === "function") {
|
||
return bridge.apiPost<T | ApiResponse<T>>(endpoint, options.body)
|
||
}
|
||
if (method === "PUT" && typeof bridge.apiPut === "function") {
|
||
return bridge.apiPut<T | ApiResponse<T>>(endpoint, options.body)
|
||
}
|
||
if (method === "DELETE" && typeof bridge.apiDelete === "function") {
|
||
return bridge.apiDelete<T | ApiResponse<T>>(endpoint)
|
||
}
|
||
return undefined
|
||
}
|
||
|
||
function unwrapApiResponse<T>(payload: T | ApiResponse<T>): T {
|
||
if (!isApiResponse<T>(payload)) {
|
||
return payload
|
||
}
|
||
if (!payload.ok) {
|
||
throw new ApiClientError(payload.error_code, payload.message, payload.details)
|
||
}
|
||
return payload.data
|
||
}
|
||
|
||
async function parseResponsePayload<T>(response: Response, endpoint: string, url: string): Promise<T | ApiResponse<T>> {
|
||
const contentType = response.headers.get("content-type") ?? ""
|
||
const isJson = contentType.includes("application/json") || contentType.includes("+json")
|
||
if (!isJson) {
|
||
const preview = (await response.text()).slice(0, 240)
|
||
throw new ApiClientError("invalid_api_response", "接口返回了非 JSON 响应", {
|
||
endpoint,
|
||
transport: "direct-fetch",
|
||
url,
|
||
status: response.status,
|
||
status_text: response.statusText,
|
||
content_type: contentType,
|
||
preview,
|
||
})
|
||
}
|
||
try {
|
||
return (await response.json()) as T | ApiResponse<T>
|
||
} catch (err) {
|
||
throw new ApiClientError("invalid_api_response", "接口返回格式不正确", {
|
||
endpoint,
|
||
transport: "direct-fetch",
|
||
url,
|
||
status: response.status,
|
||
status_text: response.statusText,
|
||
content_type: contentType,
|
||
reason: err instanceof Error ? err.message : String(err),
|
||
})
|
||
}
|
||
}
|
||
|
||
function isApiResponse<T>(payload: T | ApiResponse<T>): payload is ApiResponse<T> {
|
||
return Boolean(payload && typeof payload === "object" && "ok" in payload)
|
||
}
|
||
|
||
function compactQuery(query?: Record<string, string | number | boolean | undefined>): Record<string, unknown> | undefined {
|
||
if (!query) {
|
||
return undefined
|
||
}
|
||
const compacted: Record<string, unknown> = {}
|
||
for (const [key, value] of Object.entries(query)) {
|
||
if (value !== undefined) {
|
||
compacted[key] = value
|
||
}
|
||
}
|
||
return compacted
|
||
}
|
||
|
||
export function buildUrl(endpoint: string, query?: Record<string, string | number | boolean | undefined>) {
|
||
const trimmed = endpoint.replace(/^\/+/, "")
|
||
const url = new URL(`${API_BASE}/${trimmed}`, window.location.origin)
|
||
for (const [key, value] of Object.entries(query ?? {})) {
|
||
if (value !== undefined) {
|
||
url.searchParams.set(key, String(value))
|
||
}
|
||
}
|
||
return `${url.pathname}${url.search}`
|
||
}
|