Files
2026-03-10 01:35:37 -05:00

53 lines
1.5 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* PocketBase 记录操作 - 创建、查询(服务端可用)
*/
import { getPocketBaseConfig } from "../config";
/** 获取 Admin Token需配置 POCKETBASE_EMAIL + POCKETBASE_PASSWORD */
export async function getAdminToken(): Promise<string | null> {
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<string, unknown>,
authToken?: string
): Promise<{ id: string; [key: string]: unknown }> {
const pb = getPocketBaseConfig();
const headers: Record<string, string> = { "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();
}