58 lines
2.1 KiB
TypeScript
58 lines
2.1 KiB
TypeScript
import { SERVER_IP, PB_PORT, PB_EMAIL, PB_PASSWORD } from '../../../../config.ts';
|
|
|
|
const PB_ENDPOINT = `http://${SERVER_IP}:${PB_PORT}`;
|
|
|
|
let token: string | null = null;
|
|
let tokenExpiry = 0;
|
|
|
|
async function ensureToken(): Promise<string> {
|
|
if (token && Date.now() < tokenExpiry) return token;
|
|
const res = await fetch(`${PB_ENDPOINT}/api/collections/_superusers/auth-with-password`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ identity: PB_EMAIL, password: PB_PASSWORD }),
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(`PB admin auth failed: ${JSON.stringify(data)}`);
|
|
token = data.token;
|
|
tokenExpiry = Date.now() + 23 * 60 * 60 * 1000;
|
|
return token!;
|
|
}
|
|
|
|
export const pbAdmin = {
|
|
async getList(collection: string, filter = '') {
|
|
const t = await ensureToken();
|
|
const params = new URLSearchParams();
|
|
if (filter) params.set('filter', filter);
|
|
params.set('perPage', '200');
|
|
const res = await fetch(`${PB_ENDPOINT}/api/collections/${collection}/records?${params}`, {
|
|
headers: { Authorization: `Bearer ${t}` },
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(`PB list ${collection}: ${JSON.stringify(data)}`);
|
|
return data.items || [];
|
|
},
|
|
|
|
async getOne(collection: string, id: string) {
|
|
const t = await ensureToken();
|
|
const res = await fetch(`${PB_ENDPOINT}/api/collections/${collection}/records/${id}`, {
|
|
headers: { Authorization: `Bearer ${t}` },
|
|
});
|
|
const data = await res.json();
|
|
if (!res.ok) throw new Error(`PB get ${collection}/${id}: ${JSON.stringify(data)}`);
|
|
return data;
|
|
},
|
|
|
|
async update(collection: string, id: string, data: Record<string, unknown>) {
|
|
const t = await ensureToken();
|
|
const res = await fetch(`${PB_ENDPOINT}/api/collections/${collection}/records/${id}`, {
|
|
method: 'PATCH',
|
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${t}` },
|
|
body: JSON.stringify(data),
|
|
});
|
|
const result = await res.json();
|
|
if (!res.ok) throw new Error(`PB update ${collection}/${id}: ${JSON.stringify(result)}`);
|
|
return result;
|
|
},
|
|
};
|