dataApi.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * Quick example (matches curl usage):
  3. * await callDataApi("Youtube/search", {
  4. * query: { gl: "US", hl: "en", q: "manus" },
  5. * })
  6. */
  7. import { ENV } from "./env";
  8. export type DataApiCallOptions = {
  9. query?: Record<string, unknown>;
  10. body?: Record<string, unknown>;
  11. pathParams?: Record<string, unknown>;
  12. formData?: Record<string, unknown>;
  13. };
  14. export async function callDataApi(
  15. apiId: string,
  16. options: DataApiCallOptions = {}
  17. ): Promise<unknown> {
  18. if (!ENV.forgeApiUrl) {
  19. throw new Error("BUILT_IN_FORGE_API_URL is not configured");
  20. }
  21. if (!ENV.forgeApiKey) {
  22. throw new Error("BUILT_IN_FORGE_API_KEY is not configured");
  23. }
  24. // Build the full URL by appending the service path to the base URL
  25. const baseUrl = ENV.forgeApiUrl.endsWith("/") ? ENV.forgeApiUrl : `${ENV.forgeApiUrl}/`;
  26. const fullUrl = new URL("webdevtoken.v1.WebDevService/CallApi", baseUrl).toString();
  27. const response = await fetch(fullUrl, {
  28. method: "POST",
  29. headers: {
  30. accept: "application/json",
  31. "content-type": "application/json",
  32. "connect-protocol-version": "1",
  33. authorization: `Bearer ${ENV.forgeApiKey}`,
  34. },
  35. body: JSON.stringify({
  36. apiId,
  37. query: options.query,
  38. body: options.body,
  39. path_params: options.pathParams,
  40. multipart_form_data: options.formData,
  41. }),
  42. });
  43. if (!response.ok) {
  44. const detail = await response.text().catch(() => "");
  45. throw new Error(
  46. `Data API request failed (${response.status} ${response.statusText})${detail ? `: ${detail}` : ""}`
  47. );
  48. }
  49. const payload = await response.json().catch(() => ({}));
  50. if (payload && typeof payload === "object" && "jsonData" in payload) {
  51. try {
  52. return JSON.parse((payload as Record<string, string>).jsonData ?? "{}");
  53. } catch {
  54. return (payload as Record<string, unknown>).jsonData;
  55. }
  56. }
  57. return payload;
  58. }