88 lines
2.7 KiB
TypeScript
88 lines
2.7 KiB
TypeScript
import type {
|
|
FindOptions,
|
|
PayloadClient,
|
|
PayloadClientResult,
|
|
} from "./types";
|
|
|
|
export class HTTPPayloadClient implements PayloadClient {
|
|
constructor(private baseURL: string) {}
|
|
|
|
private async request<T>(path: string, options?: RequestInit): Promise<T> {
|
|
const response = await fetch(`${this.baseURL}${path}`, {
|
|
headers: { "Content-Type": "application/json" },
|
|
...options,
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(
|
|
`Payload API error: ${response.status} ${response.statusText}`
|
|
);
|
|
}
|
|
return response.json() as Promise<T>;
|
|
}
|
|
|
|
async find<T = Record<string, unknown>>(
|
|
collection: string,
|
|
options?: FindOptions
|
|
): Promise<PayloadClientResult<T>> {
|
|
const params = new URLSearchParams();
|
|
if (options?.limit) params.set("limit", String(options.limit));
|
|
if (options?.page) params.set("page", String(options.page));
|
|
if (options?.sort) params.set("sort", options.sort);
|
|
if (options?.depth) params.set("depth", String(options.depth));
|
|
if (options?.where) params.set("where", JSON.stringify(options.where));
|
|
const query = params.toString();
|
|
return this.request<PayloadClientResult<T>>(
|
|
`/api/${collection}${query ? `?${query}` : ""}`
|
|
);
|
|
}
|
|
|
|
async findByID<T = Record<string, unknown>>(
|
|
collection: string,
|
|
id: string,
|
|
options?: { depth?: number }
|
|
): Promise<T> {
|
|
const params = new URLSearchParams();
|
|
if (options?.depth) params.set("depth", String(options.depth));
|
|
const query = params.toString();
|
|
return this.request<T>(
|
|
`/api/${collection}/${id}${query ? `?${query}` : ""}`
|
|
);
|
|
}
|
|
|
|
async create<T = Record<string, unknown>>(
|
|
collection: string,
|
|
data: Record<string, unknown>,
|
|
options?: { depth?: number }
|
|
): Promise<T> {
|
|
const params = new URLSearchParams();
|
|
if (options?.depth) params.set("depth", String(options.depth));
|
|
const query = params.toString();
|
|
return this.request<T>(
|
|
`/api/${collection}${query ? `?${query}` : ""}`,
|
|
{ method: "POST", body: JSON.stringify(data) }
|
|
);
|
|
}
|
|
|
|
async update<T = Record<string, unknown>>(
|
|
collection: string,
|
|
id: string,
|
|
data: Record<string, unknown>,
|
|
options?: { depth?: number }
|
|
): Promise<T> {
|
|
const params = new URLSearchParams();
|
|
if (options?.depth) params.set("depth", String(options.depth));
|
|
const query = params.toString();
|
|
return this.request<T>(
|
|
`/api/${collection}/${id}${query ? `?${query}` : ""}`,
|
|
{ method: "PATCH", body: JSON.stringify(data) }
|
|
);
|
|
}
|
|
|
|
async delete<T = Record<string, unknown>>(
|
|
collection: string,
|
|
id: string
|
|
): Promise<T> {
|
|
return this.request<T>(`/api/${collection}/${id}`, { method: "DELETE" });
|
|
}
|
|
}
|