54 行
1.8 KiB
TypeScript
54 行
1.8 KiB
TypeScript
|
|
import { API_BASE } from "./endpoints"
|
||
|
|
import type { ApiResponse } from "../types/api"
|
||
|
|
|
||
|
|
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 request<T>(
|
||
|
|
endpoint: string,
|
||
|
|
options: {
|
||
|
|
method?: "GET" | "POST" | "PUT" | "DELETE"
|
||
|
|
query?: Record<string, string | number | boolean | undefined>
|
||
|
|
body?: unknown
|
||
|
|
} = {},
|
||
|
|
): Promise<T> {
|
||
|
|
const response = await fetch(buildUrl(endpoint, options.query), {
|
||
|
|
method: options.method ?? "GET",
|
||
|
|
headers: options.body === undefined ? undefined : { "Content-Type": "application/json" },
|
||
|
|
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
||
|
|
})
|
||
|
|
const payload = (await response.json()) as ApiResponse<T>
|
||
|
|
if (!payload.ok) {
|
||
|
|
throw new ApiClientError(payload.error_code, payload.message, payload.details)
|
||
|
|
}
|
||
|
|
return payload.data
|
||
|
|
}
|
||
|
|
|
||
|
|
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}`
|
||
|
|
}
|