import type { WebinyConfig } from "../types.js"; import { Result } from "../Result.js"; import { HttpError, ApiError, NetworkError } from "../errors.js"; import { resolveHeaders } from "../utils/resolveHeaders.js"; export async function executeGraphQL( config: WebinyConfig, fetchFn: typeof fetch, query: string, variables: Record = {} ): Promise> { const url = `${config.endpoint}/graphql`; let response: Response; try { const body = JSON.stringify({ query, variables }); const headers: Record = { "Content-Type": "application/json", "x-tenant": config.tenant ?? "root", ...(await resolveHeaders(config.headers)) }; // Only add Authorization header if token is provided and not already set in custom headers. if (config.token && !headers.Authorization) { const token = typeof config.token === "function" ? await config.token() : config.token; headers.Authorization = `Bearer ${token}`; } response = await fetchFn(url, { method: "POST", headers, body }); } catch (error) { return Result.fail( new NetworkError(error instanceof Error ? error.message : "Network request failed") ); } if (!response.ok) { return Result.fail( new HttpError(response.status, `HTTP error! status: ${response.status}`) ); } let result: any; try { result = await response.json(); } catch { return Result.fail(new NetworkError("Failed to parse response JSON")); } if (result.errors) { const error = result.errors[0]; return Result.fail(new ApiError(error?.message || "GraphQL error", error?.code)); } return Result.ok(result.data); }