/** * PocketBase 记录操作 - 创建、查询(服务端可用) */ import { getPocketBaseConfig } from "../config"; /** 获取 Admin Token(需配置 POCKETBASE_EMAIL + POCKETBASE_PASSWORD) */ export async function getAdminToken(): Promise { const email = process.env.POCKETBASE_EMAIL; const password = process.env.POCKETBASE_PASSWORD; if (!email || !password) return null; const pb = getPocketBaseConfig(); const res = await fetch(`${pb.url}/api/admins/auth-with-password`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ identity: email, password }), }); if (!res.ok) return null; const data = await res.json(); return data?.token ?? null; } /** 创建记录 */ export async function createRecord( collection: string, data: Record, authToken?: string ): Promise<{ id: string; [key: string]: unknown }> { const pb = getPocketBaseConfig(); const headers: Record = { "Content-Type": "application/json" }; if (authToken) headers["Authorization"] = authToken; const res = await fetch(`${pb.url}/api/collections/${collection}/records`, { method: "POST", headers, body: JSON.stringify(data), }); if (!res.ok) { const errText = await res.text(); let errMsg = "创建失败"; try { const errJson = JSON.parse(errText); if (errJson?.message) errMsg = errJson.message; } catch { if (errText.length < 200) errMsg = errText; } throw new Error(errMsg); } return res.json(); }