api_manager.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const axios = require("axios").default;
  2. const qs = require("qs");
  3. /// Helper functions to route to the appropriate API Call.
  4. async function makeApiCall(context, data) {
  5. var callName = data["callName"] || "";
  6. var variables = data["variables"] || {};
  7. const callMap = {};
  8. if (!(callName in callMap)) {
  9. return {
  10. statusCode: 400,
  11. error: `API Call "${callName}" not defined as private API.`,
  12. };
  13. }
  14. var apiCall = callMap[callName];
  15. var response = await apiCall(context, variables);
  16. return response;
  17. }
  18. async function makeApiRequest({
  19. method,
  20. url,
  21. headers,
  22. params,
  23. body,
  24. returnBody,
  25. isStreamingApi,
  26. }) {
  27. return axios
  28. .request({
  29. method: method,
  30. url: url,
  31. headers: headers,
  32. params: params,
  33. responseType: isStreamingApi ? "stream" : "json",
  34. ...(body && { data: body }),
  35. })
  36. .then((response) => {
  37. return {
  38. statusCode: response.status,
  39. headers: response.headers,
  40. ...(returnBody && { body: response.data }),
  41. isStreamingApi: isStreamingApi,
  42. };
  43. })
  44. .catch(function (error) {
  45. return {
  46. statusCode: error.response.status,
  47. headers: error.response.headers,
  48. ...(returnBody && { body: error.response.data }),
  49. error: error.message,
  50. };
  51. });
  52. }
  53. const _unauthenticatedResponse = {
  54. statusCode: 401,
  55. headers: {},
  56. error: "API call requires authentication",
  57. };
  58. function createBody({ headers, params, body, bodyType }) {
  59. switch (bodyType) {
  60. case "JSON":
  61. headers["Content-Type"] = "application/json";
  62. return body;
  63. case "TEXT":
  64. headers["Content-Type"] = "text/plain";
  65. return body;
  66. case "X_WWW_FORM_URL_ENCODED":
  67. headers["Content-Type"] = "application/x-www-form-urlencoded";
  68. return qs.stringify(params);
  69. }
  70. }
  71. function escapeStringForJson(val) {
  72. if (typeof val !== "string") {
  73. return val;
  74. }
  75. return val
  76. .replace(/[\\]/g, "\\\\")
  77. .replace(/["]/g, '\\"')
  78. .replace(/[\n]/g, "\\n")
  79. .replace(/[\t]/g, "\\t");
  80. }
  81. module.exports = { makeApiCall };