You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.9 KiB

11 months ago
  1. const { safeJsonParse } = require("../../http");
  2. /**
  3. * Execute an API call flow step
  4. * @param {Object} config Flow step configuration
  5. * @param {Object} context Execution context with introspect function
  6. * @returns {Promise<string>} Response data
  7. */
  8. async function executeApiCall(config, context) {
  9. const { url, method, headers = [], body, bodyType, formData } = config;
  10. const { introspect } = context;
  11. introspect(`Making ${method} request to external API...`);
  12. const requestConfig = {
  13. method,
  14. headers: headers.reduce((acc, h) => ({ ...acc, [h.key]: h.value }), {}),
  15. };
  16. if (["POST", "PUT", "PATCH"].includes(method)) {
  17. if (bodyType === "form") {
  18. const formDataObj = new URLSearchParams();
  19. formData.forEach(({ key, value }) => formDataObj.append(key, value));
  20. requestConfig.body = formDataObj.toString();
  21. requestConfig.headers["Content-Type"] =
  22. "application/x-www-form-urlencoded";
  23. } else if (bodyType === "json") {
  24. const parsedBody = safeJsonParse(body, null);
  25. if (parsedBody !== null) {
  26. requestConfig.body = JSON.stringify(parsedBody);
  27. }
  28. requestConfig.headers["Content-Type"] = "application/json";
  29. } else if (bodyType === "text") {
  30. requestConfig.body = String(body);
  31. } else {
  32. requestConfig.body = body;
  33. }
  34. }
  35. try {
  36. introspect(`Sending body to ${url}: ${requestConfig?.body || "No body"}`);
  37. const response = await fetch(url, requestConfig);
  38. if (!response.ok) {
  39. introspect(`Request failed with status ${response.status}`);
  40. throw new Error(`HTTP error! status: ${response.status}`);
  41. }
  42. introspect(`API call completed`);
  43. return await response
  44. .text()
  45. .then((text) =>
  46. safeJsonParse(text, "Failed to parse output from API call block")
  47. );
  48. } catch (error) {
  49. console.error(error);
  50. throw new Error(`API Call failed: ${error.message}`);
  51. }
  52. }
  53. module.exports = executeApiCall;