| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- const axios = require("axios").default;
- const qs = require("qs");
- /// Helper functions to route to the appropriate API Call.
- async function makeApiCall(context, data) {
- var callName = data["callName"] || "";
- var variables = data["variables"] || {};
- const callMap = {};
- if (!(callName in callMap)) {
- return {
- statusCode: 400,
- error: `API Call "${callName}" not defined as private API.`,
- };
- }
- var apiCall = callMap[callName];
- var response = await apiCall(context, variables);
- return response;
- }
- async function makeApiRequest({
- method,
- url,
- headers,
- params,
- body,
- returnBody,
- isStreamingApi,
- }) {
- return axios
- .request({
- method: method,
- url: url,
- headers: headers,
- params: params,
- responseType: isStreamingApi ? "stream" : "json",
- ...(body && { data: body }),
- })
- .then((response) => {
- return {
- statusCode: response.status,
- headers: response.headers,
- ...(returnBody && { body: response.data }),
- isStreamingApi: isStreamingApi,
- };
- })
- .catch(function (error) {
- return {
- statusCode: error.response.status,
- headers: error.response.headers,
- ...(returnBody && { body: error.response.data }),
- error: error.message,
- };
- });
- }
- const _unauthenticatedResponse = {
- statusCode: 401,
- headers: {},
- error: "API call requires authentication",
- };
- function createBody({ headers, params, body, bodyType }) {
- switch (bodyType) {
- case "JSON":
- headers["Content-Type"] = "application/json";
- return body;
- case "TEXT":
- headers["Content-Type"] = "text/plain";
- return body;
- case "X_WWW_FORM_URL_ENCODED":
- headers["Content-Type"] = "application/x-www-form-urlencoded";
- return qs.stringify(params);
- }
- }
- function escapeStringForJson(val) {
- if (typeof val !== "string") {
- return val;
- }
- return val
- .replace(/[\\]/g, "\\\\")
- .replace(/["]/g, '\\"')
- .replace(/[\n]/g, "\\n")
- .replace(/[\t]/g, "\\t");
- }
- module.exports = { makeApiCall };
|