import { getLogger } from '../lib/logger.js' import { getConfig } from '../config.js' const log = getLogger('payload-client') export class PayloadClient { private baseUrl: string private apiKey?: string constructor() { const config = getConfig() this.baseUrl = config.PAYLOAD_API_URL this.apiKey = config.PAYLOAD_API_KEY } async find( collection: string, query: Record = {}, ): Promise<{ docs: T[]; totalDocs: number }> { const params = new URLSearchParams() for (const [key, value] of Object.entries(query)) { if (value !== undefined) { params.set(key, String(value)) } } const url = `${this.baseUrl}/${collection}?${params.toString()}` const response = await this.request<{ docs: T[]; totalDocs: number }>(url) return response } async findByID(collection: string, id: number | string): Promise { const url = `${this.baseUrl}/${collection}/${id}` return this.request(url) } async create( collection: string, data: Record, ): Promise { const url = `${this.baseUrl}/${collection}` return this.request(url, { method: 'POST', body: JSON.stringify(data), }) } private async request(url: string, init?: RequestInit): Promise { const headers: Record = { 'Content-Type': 'application/json', } if (this.apiKey) { headers['Authorization'] = `Bearer ${this.apiKey}` } const response = await fetch(url, { ...init, headers: { ...headers, ...init?.headers }, }) if (!response.ok) { const body = await response.text().catch(() => '') log.error( { url, status: response.status, body: body.slice(0, 200) }, 'Payload API error', ) throw new Error(`Payload API error: ${response.status}`) } return response.json() as Promise } }