feat(api): add account mutation clients

This commit is contained in:
zetaloop
2026-04-25 14:13:45 +08:00
parent 70230483f8
commit d7cc6b0141
4 changed files with 98 additions and 5 deletions
+67
View File
@@ -1,3 +1,36 @@
import { isApiError } from "@/lib/errors"
export type UploadFileType = "avatar" | "chat" | "post" | "verification" | "dispute"
function getCookieValue(name: string): string | null {
if (typeof document === "undefined") return null
if (!document.cookie) return null
for (const part of document.cookie.split("; ")) {
if (part.startsWith(`${name}=`)) return part.slice(name.length + 1)
}
return null
}
async function readJsonBody(res: Response): Promise<{ json: unknown | null; text: string }> {
const text = await res.text()
if (!text) return { json: null, text: "" }
try {
return { json: JSON.parse(text) as unknown, text }
} catch {
return { json: null, text }
}
}
function messageFromJson(json: unknown): string | undefined {
if (typeof json !== "object" || json === null) return undefined
const value = json as { message?: unknown; msg?: unknown }
if (typeof value.message === "string") return value.message
if (typeof value.msg === "string") return value.msg
return undefined
}
export async function getFileById(fileId: string): Promise<Blob> {
const res = await fetch(`/api/v1/files?key=${encodeURIComponent(fileId)}`)
@@ -31,3 +64,37 @@ export async function getFileById(fileId: string): Promise<Blob> {
throw { code, msg }
}
export async function uploadFile(file: File, type: UploadFileType): Promise<string> {
const formData = new FormData()
formData.set("type", type)
formData.set("file", file)
const headers = new Headers()
const xsrfToken = getCookieValue("__Host-XSRF-TOKEN")
if (xsrfToken) headers.set("XSRF-TOKEN", xsrfToken)
const res = await fetch("/api/v1/upload", {
method: "POST",
headers,
body: formData,
})
const { json, text } = await readJsonBody(res)
if (res.ok) {
if (typeof json === "object" && json !== null) {
const value = json as { url?: unknown }
if (typeof value.url === "string") return value.url
}
throw { code: 500, msg: "上传响应缺少文件地址" }
}
if (res.status === 401) throw new Error("UNAUTHORIZED")
if (isApiError(json)) throw json
throw {
code: res.status,
msg: messageFromJson(json) ?? (text || res.statusText || "Request failed"),
}
}