drapcode-utility 2.0.0 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/build/encryption/KMS.js +54 -102
  2. package/build/encryption/crypt.d.ts +4 -2
  3. package/build/encryption/crypt.js +76 -91
  4. package/build/encryption/file.d.ts +0 -2
  5. package/build/encryption/file.js +14 -130
  6. package/build/encryption/index.js +162 -334
  7. package/build/encryption/utility.js +7 -10
  8. package/build/errors/app-error.js +9 -27
  9. package/build/errors/axios-error.js +3 -3
  10. package/build/errors/bad-request-error.js +10 -28
  11. package/build/errors/custom-error.js +5 -23
  12. package/build/errors/not-found.js +9 -27
  13. package/build/format-fields/index.d.ts +0 -1
  14. package/build/format-fields/index.js +32 -65
  15. package/build/index.d.ts +1 -4
  16. package/build/index.js +1 -4
  17. package/build/middlewares/error-logger.d.ts +1 -1
  18. package/build/middlewares/error-logger.js +29 -29
  19. package/build/middlewares/redis/request-log.js +24 -74
  20. package/build/query/queryBuilder.d.ts +9 -0
  21. package/build/query/queryBuilder.js +567 -0
  22. package/build/utils/check-error.d.ts +15 -8
  23. package/build/utils/check-error.js +71 -160
  24. package/build/utils/common-util.d.ts +40 -39
  25. package/build/utils/common-util.js +60 -59
  26. package/build/utils/date-util.d.ts +28 -7
  27. package/build/utils/date-util.js +180 -127
  28. package/build/utils/file-util.d.ts +51 -6
  29. package/build/utils/file-util.js +36 -40
  30. package/build/utils/prepare-query.js +70 -43
  31. package/build/utils/project-util.d.ts +43 -5
  32. package/build/utils/project-util.js +176 -121
  33. package/build/utils/query-parser.d.ts +1 -1
  34. package/build/utils/query-parser.js +289 -342
  35. package/build/utils/query-utils.d.ts +2 -2
  36. package/build/utils/query-utils.js +103 -116
  37. package/build/utils/rest-client.js +236 -328
  38. package/build/utils/s3-util.js +238 -469
  39. package/build/utils/token.js +34 -81
  40. package/build/utils/util.d.ts +58 -13
  41. package/build/utils/util.js +424 -494
  42. package/build/utils/uuid-generator.d.ts +20 -1
  43. package/build/utils/uuid-generator.js +111 -47
  44. package/package.json +7 -5
  45. package/build/middlewares/interceptor-logger-new.d.ts +0 -2
  46. package/build/middlewares/interceptor-logger-new.js +0 -53
  47. package/build/middlewares/interceptor-logger.d.ts +0 -2
  48. package/build/middlewares/interceptor-logger.js +0 -52
  49. package/build/utils/query-parser-new.d.ts +0 -1
  50. package/build/utils/query-parser-new.js +0 -541
@@ -1,266 +1,191 @@
1
1
  "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
50
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
51
4
  };
52
5
  Object.defineProperty(exports, "__esModule", { value: true });
53
6
  exports.callCurlRequest = void 0;
54
- var axios_1 = __importDefault(require("axios"));
55
- var util_1 = require("./util");
56
- var drapcode_logger_1 = require("drapcode-logger");
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const util_1 = require("./util");
9
+ const drapcode_logger_1 = require("drapcode-logger");
57
10
  var FormData = require("form-data");
58
11
  var fs = require("fs");
59
- var qs = require("qs");
60
- var callCurlRequest = function (setting, user, tenant, userSetting, subTenant, data, timeout, timeoutMessage, envConstants, downloadBytes, requestDataType, wrapJsonDataInArray, projectId, dataTransferObject, isRawJSON, browserStorageData) {
61
- if (user === void 0) { user = {}; }
62
- if (tenant === void 0) { tenant = {}; }
63
- if (userSetting === void 0) { userSetting = {}; }
64
- if (subTenant === void 0) { subTenant = {}; }
65
- if (data === void 0) { data = {}; }
66
- if (timeout === void 0) { timeout = 0; }
67
- if (timeoutMessage === void 0) { timeoutMessage = ""; }
68
- if (envConstants === void 0) { envConstants = {}; }
69
- if (downloadBytes === void 0) { downloadBytes = false; }
70
- if (requestDataType === void 0) { requestDataType = ""; }
71
- if (wrapJsonDataInArray === void 0) { wrapJsonDataInArray = false; }
72
- if (projectId === void 0) { projectId = ""; }
73
- if (dataTransferObject === void 0) { dataTransferObject = {}; }
74
- if (isRawJSON === void 0) { isRawJSON = false; }
75
- if (browserStorageData === void 0) { browserStorageData = {}; }
76
- return __awaiter(void 0, void 0, void 0, function () {
77
- var url, params, methodType, authType, requestHeader, accessToken, _a, headers, isMultipart, files, _b, awsSignPluginConfig, _c, sessionValue, sessionFormValue, sessionStorageValue, localStorageValue, cookiesValue, headerValue, requestParams, toDeleteFiles, objectArray, settingsHeaderObjectArray, dataHeaderObjectArray, mergedHeaders_1, settingsHasContentType_1, settingsContentTypeKey_1, headerContentTypeUrlEncoded, isUrlEncoded, result, errorMessage, error_1, err, errData, errStatus;
78
- return __generator(this, function (_d) {
79
- switch (_d.label) {
80
- case 0:
81
- url = setting.url, params = setting.params, methodType = setting.methodType, authType = setting.authType, requestHeader = setting.requestHeader, accessToken = setting.accessToken, _a = setting.headers, headers = _a === void 0 ? [] : _a, isMultipart = setting.isMultipart, files = setting.files, _b = setting.awsSignPluginConfig, awsSignPluginConfig = _b === void 0 ? null : _b;
82
- _c = browserStorageData || {}, sessionValue = _c.sessionValue, sessionFormValue = _c.sessionFormValue, sessionStorageValue = _c.sessionStorageData, localStorageValue = _c.localStorageData, cookiesValue = _c.cookiesData;
83
- drapcode_logger_1.logger.info("STEP 1 Replacing placeholder key values...", {
84
- label: projectId,
85
- });
86
- // Uncomment below only when needed for debugging
87
- // logger.info(
88
- // `STEP 1 Replacing URL Session Value: ${sessionValue ? JSON.stringify(sessionValue) : ""
89
- // }, Session Form Value: ${sessionFormValue ? JSON.stringify(sessionFormValue) : ""
90
- // }, Browser Storage Data: ${browserStorageData ? JSON.stringify(browserStorageData) : ""
91
- // }, Session Storage: ${sessionStorageValue ? JSON.stringify(sessionStorageValue) : ""
92
- // }, Local Storage: ${localStorageValue ? JSON.stringify(localStorageValue) : ""
93
- // }, Session Cookies: ${cookiesValue ? JSON.stringify(cookiesValue) : ""
94
- // }, Headers: ${headers ? JSON.stringify(headers) : ""}`,
95
- // { label: projectId }
96
- // );
97
- if (url.includes("{{current_user.") &&
98
- (!user || Object.keys(user).length == 0)) {
99
- drapcode_logger_1.logger.info("**2 Sending back", { label: projectId });
100
- return [2 /*return*/, prepareReturnObject("User is not logged in. URL is wrong")];
101
- }
102
- if (data || user || tenant || envConstants || userSetting || subTenant) {
103
- url = (0, util_1.replaceDataValueIntoExpression)(url, data, user, tenant, userSetting, subTenant, sessionValue, envConstants, sessionFormValue, localStorageValue, cookiesValue);
104
- }
105
- if (!url) {
106
- drapcode_logger_1.logger.info("**5 url not found", { label: projectId });
107
- return [2 /*return*/, prepareReturnObject("URL is wrong")];
108
- }
109
- drapcode_logger_1.logger.info("STEP 2: URL replaced and replacing header", {
110
- label: projectId,
111
- });
112
- headerValue = (0, util_1.mergeObjects)(headers, data, user, tenant, userSetting, subTenant, sessionValue, envConstants, sessionFormValue, dataTransferObject, localStorageValue, cookiesValue);
113
- headerValue = {
114
- headers: __assign({}, headerValue),
115
- };
116
- drapcode_logger_1.logger.info("STEP 3: Replacing Header Auth", { label: projectId });
117
- drapcode_logger_1.logger.info("accessToken: ".concat(accessToken, " authType: ").concat(authType), {
118
- label: projectId,
119
- });
120
- if (accessToken) {
121
- headerValue.headers[requestHeader] = authType
122
- ? "".concat(authType, " ").concat(accessToken)
123
- : accessToken;
124
- }
125
- if (params && params.length) {
126
- requestParams = (0, util_1.mergeObjects)(params, data, user, tenant, userSetting, subTenant, sessionValue, envConstants, sessionFormValue, dataTransferObject, localStorageValue, cookiesValue);
127
- headerValue.params = requestParams;
128
- }
129
- //unflat data before api call
130
- data = data ? (0, util_1.unflattenObject)(data) : data;
131
- drapcode_logger_1.logger.info("Before headers: ".concat(JSON.stringify(headerValue.headers)), {
132
- label: projectId,
133
- });
134
- drapcode_logger_1.logger.info("isMultipart: ".concat(isMultipart), { label: projectId });
135
- toDeleteFiles = [];
136
- if (isMultipart || (requestDataType && requestDataType === "FORM_DATA")) {
137
- objectArray = Object.entries(data);
138
- data = new FormData();
139
- objectArray.forEach(function (_a) {
140
- var key = _a[0], value = _a[1];
141
- if (files && files.includes(key)) {
142
- drapcode_logger_1.logger.info("".concat(key, " files.includes(key): ").concat(files.includes(key)), {
143
- label: projectId,
144
- });
145
- drapcode_logger_1.logger.info("value: ".concat(value), { label: projectId });
146
- data.append(key, fs.createReadStream(value));
147
- toDeleteFiles.push(value);
148
- }
149
- else {
150
- data.append(key, value);
151
- }
152
- });
153
- settingsHeaderObjectArray = Object.entries(headerValue.headers);
154
- dataHeaderObjectArray = Object.entries(data.getHeaders());
155
- mergedHeaders_1 = {};
156
- settingsHasContentType_1 = false;
157
- settingsContentTypeKey_1 = "";
158
- settingsHeaderObjectArray.forEach(function (_a) {
159
- var key = _a[0], value = _a[1];
160
- if (key && key.toLowerCase() === "content-type") {
161
- settingsHasContentType_1 = true;
162
- settingsContentTypeKey_1 = key;
163
- }
164
- else {
165
- mergedHeaders_1[key] = value;
166
- }
167
- });
168
- dataHeaderObjectArray.forEach(function (_a) {
169
- var key = _a[0], value = _a[1];
170
- if (key && key === "content-type" && settingsHasContentType_1) {
171
- mergedHeaders_1[settingsContentTypeKey_1] = value;
172
- }
173
- else {
174
- mergedHeaders_1[key] = value;
175
- }
176
- });
177
- drapcode_logger_1.logger.info("*** merged headers :>> ".concat(mergedHeaders_1), {
178
- label: projectId,
179
- });
180
- headerValue.headers = __assign({}, mergedHeaders_1);
181
- }
182
- drapcode_logger_1.logger.info("After headers ".concat(JSON.stringify(headerValue.headers)), {
183
- label: projectId,
184
- });
185
- drapcode_logger_1.logger.info("** App Environment: ".concat(process.env.APP_ENV), {
186
- label: projectId,
187
- });
188
- headerContentTypeUrlEncoded = setting.headers.find(function (head) {
189
- if (head === void 0) { head = {}; }
190
- return head.key &&
191
- head.key.toLowerCase() === "content-type" &&
192
- head.value === "application/x-www-form-urlencoded";
193
- });
194
- isUrlEncoded = !!headerContentTypeUrlEncoded;
195
- drapcode_logger_1.logger.info("** isUrlEncoded: ".concat(isUrlEncoded), { label: projectId });
196
- //Add Environment in Header for Lambda USE
197
- headerValue.headers["x-project-env"] = process.env.APP_ENV;
198
- if (downloadBytes) {
199
- headerValue["responseType"] = "stream";
200
- }
201
- _d.label = 1;
202
- case 1:
203
- _d.trys.push([1, 3, , 4]);
204
- result = null;
205
- if (!isRawJSON) {
206
- if (requestDataType === "FORM_URL_ENCODED" || isUrlEncoded) {
207
- data = qs.stringify(data);
208
- drapcode_logger_1.logger.info("**17 Encoded data:", data, { label: projectId });
209
- }
210
- if (requestDataType === "NO_BODY_DATA")
211
- data = {};
212
- }
213
- return [4 /*yield*/, makeAxiosCall(projectId, methodType, url, headerValue, data, timeout, wrapJsonDataInArray, awsSignPluginConfig)];
214
- case 2:
215
- result = _d.sent();
216
- drapcode_logger_1.logger.info("result.headers: ".concat(result === null || result === void 0 ? void 0 : result.headers), { label: projectId });
217
- if (!result) {
218
- errorMessage = "No Response from Server";
219
- return [2 /*return*/, prepareReturnObject(errorMessage)];
220
- }
221
- drapcode_logger_1.logger.info("result.status: ".concat(result === null || result === void 0 ? void 0 : result.status), { label: projectId });
222
- deleteLocalFiles(isMultipart, toDeleteFiles);
223
- return [2 /*return*/, prepareReturnObject(result.data, result.status, true, result === null || result === void 0 ? void 0 : result.headers)];
224
- case 3:
225
- error_1 = _d.sent();
226
- deleteLocalFiles(isMultipart, toDeleteFiles);
227
- err = error_1;
228
- errData = null, errStatus = 400;
229
- if (err.response) {
230
- drapcode_logger_1.logger.info("err.response.data: ".concat(err.response.data ? JSON.stringify(err.response.data) : ""), {
231
- label: projectId,
232
- });
233
- drapcode_logger_1.logger.info("err.response.status: ".concat(err.response.status), {
234
- label: projectId,
235
- });
236
- drapcode_logger_1.logger.info("err.response.headers: ".concat(err.response.headers ? JSON.stringify(err.response.headers) : ""), {
237
- label: projectId,
238
- });
239
- errData = err.response.data;
240
- errStatus = err.response.status;
241
- }
242
- else if (err.request) {
243
- errData = "No Response Received from the API";
244
- drapcode_logger_1.logger.info("err.request: ".concat(err.request), { label: projectId });
245
- }
246
- else {
247
- if (err.message.includes("ECONNABORTED")) {
248
- errData = timeoutMessage || "No response received from the REST API";
249
- }
250
- else {
251
- errData = err.message;
252
- }
253
- }
254
- return [2 /*return*/, prepareReturnObject(errData, errStatus)];
255
- case 4: return [2 /*return*/];
12
+ const qs = require("qs");
13
+ const callCurlRequest = async (setting, user = {}, tenant = {}, userSetting = {}, subTenant = {}, data = {}, timeout = 0, timeoutMessage = "", envConstants = {}, downloadBytes = false, requestDataType = "", wrapJsonDataInArray = false, projectId = "", dataTransferObject = {}, isRawJSON = false, browserStorageData = {}) => {
14
+ let { url, params, methodType, authType, requestHeader, accessToken, headers = [], isMultipart, files, awsSignPluginConfig = null, } = setting;
15
+ const { sessionValue, sessionFormValue,
16
+ // sessionStorageData: sessionStorageValue,
17
+ localStorageData: localStorageValue, cookiesData: cookiesValue, } = browserStorageData || {};
18
+ drapcode_logger_1.logger.info(`STEP 1 Replacing placeholder key values...`, {
19
+ label: projectId,
20
+ });
21
+ // Uncomment below only when needed for debugging
22
+ // logger.info(
23
+ // `STEP 1 Replacing URL Session Value: ${sessionValue ? JSON.stringify(sessionValue) : ""
24
+ // }, Session Form Value: ${sessionFormValue ? JSON.stringify(sessionFormValue) : ""
25
+ // }, Browser Storage Data: ${browserStorageData ? JSON.stringify(browserStorageData) : ""
26
+ // }, Session Storage: ${sessionStorageValue ? JSON.stringify(sessionStorageValue) : ""
27
+ // }, Local Storage: ${localStorageValue ? JSON.stringify(localStorageValue) : ""
28
+ // }, Session Cookies: ${cookiesValue ? JSON.stringify(cookiesValue) : ""
29
+ // }, Headers: ${headers ? JSON.stringify(headers) : ""}`,
30
+ // { label: projectId }
31
+ // );
32
+ if (url.includes("{{current_user.") &&
33
+ (!user || Object.keys(user).length == 0)) {
34
+ drapcode_logger_1.logger.info("**2 Sending back", { label: projectId });
35
+ return prepareReturnObject("User is not logged in. URL is wrong");
36
+ }
37
+ if (data || user || tenant || envConstants || userSetting || subTenant) {
38
+ url = (0, util_1.replaceDataValueIntoExpression)(url, data, user, tenant, userSetting, subTenant, sessionValue, envConstants, sessionFormValue, localStorageValue, cookiesValue);
39
+ }
40
+ if (!url) {
41
+ drapcode_logger_1.logger.info("**5 url not found", { label: projectId });
42
+ return prepareReturnObject("URL is wrong");
43
+ }
44
+ drapcode_logger_1.logger.info("STEP 2: URL replaced and replacing header", {
45
+ label: projectId,
46
+ });
47
+ let headerValue = (0, util_1.mergeObjects)(headers, data, user, tenant, userSetting, subTenant, sessionValue, envConstants, sessionFormValue, dataTransferObject, localStorageValue, cookiesValue);
48
+ headerValue = {
49
+ headers: { ...headerValue },
50
+ };
51
+ drapcode_logger_1.logger.info("STEP 3: Replacing Header Auth", { label: projectId });
52
+ drapcode_logger_1.logger.info(`accessToken: ${accessToken} authType: ${authType}`, {
53
+ label: projectId,
54
+ });
55
+ if (accessToken) {
56
+ headerValue.headers[requestHeader] = authType
57
+ ? `${authType} ${accessToken}`
58
+ : accessToken;
59
+ }
60
+ if (params && params.length) {
61
+ let requestParams = (0, util_1.mergeObjects)(params, data, user, tenant, userSetting, subTenant, sessionValue, envConstants, sessionFormValue, dataTransferObject, localStorageValue, cookiesValue);
62
+ headerValue.params = requestParams;
63
+ }
64
+ //unflat data before api call
65
+ data = data ? (0, util_1.unflattenObject)(data) : data;
66
+ drapcode_logger_1.logger.info(`Before headers: ${JSON.stringify(headerValue.headers)}`, {
67
+ label: projectId,
68
+ });
69
+ drapcode_logger_1.logger.info(`isMultipart: ${isMultipart}`, { label: projectId });
70
+ const toDeleteFiles = [];
71
+ if (isMultipart || (requestDataType && requestDataType === "FORM_DATA")) {
72
+ const objectArray = Object.entries(data);
73
+ data = new FormData();
74
+ objectArray.forEach(([key, value]) => {
75
+ if (files && files.includes(key)) {
76
+ drapcode_logger_1.logger.info(`${key} files.includes(key): ${files.includes(key)}`, {
77
+ label: projectId,
78
+ });
79
+ drapcode_logger_1.logger.info(`value: ${value}`, { label: projectId });
80
+ data.append(key, fs.createReadStream(value));
81
+ toDeleteFiles.push(value);
82
+ }
83
+ else {
84
+ data.append(key, value);
85
+ }
86
+ });
87
+ //Handling double entry of Content-Type in case of Multipart form-data
88
+ const settingsHeaderObjectArray = Object.entries(headerValue.headers);
89
+ const dataHeaderObjectArray = Object.entries(data.getHeaders());
90
+ let mergedHeaders = {};
91
+ let settingsHasContentType = false;
92
+ let settingsContentTypeKey = "";
93
+ settingsHeaderObjectArray.forEach(([key, value]) => {
94
+ if (key && key.toLowerCase() === "content-type") {
95
+ settingsHasContentType = true;
96
+ settingsContentTypeKey = key;
97
+ }
98
+ else {
99
+ mergedHeaders[key] = value;
256
100
  }
257
101
  });
102
+ dataHeaderObjectArray.forEach(([key, value]) => {
103
+ if (key && key === "content-type" && settingsHasContentType) {
104
+ mergedHeaders[settingsContentTypeKey] = value;
105
+ }
106
+ else {
107
+ mergedHeaders[key] = value;
108
+ }
109
+ });
110
+ drapcode_logger_1.logger.info(`*** merged headers :>> ${mergedHeaders}`, {
111
+ label: projectId,
112
+ });
113
+ headerValue.headers = {
114
+ ...mergedHeaders,
115
+ };
116
+ }
117
+ drapcode_logger_1.logger.info(`After headers ${JSON.stringify(headerValue.headers)}`, {
118
+ label: projectId,
119
+ });
120
+ drapcode_logger_1.logger.info(`** App Environment: ${process.env.APP_ENV}`, {
121
+ label: projectId,
258
122
  });
123
+ const headerContentTypeUrlEncoded = setting.headers.find((head = {}) => head.key &&
124
+ head.key.toLowerCase() === "content-type" &&
125
+ head.value === "application/x-www-form-urlencoded");
126
+ const isUrlEncoded = !!headerContentTypeUrlEncoded;
127
+ drapcode_logger_1.logger.info(`** isUrlEncoded: ${isUrlEncoded}`, { label: projectId });
128
+ //Add Environment in Header for Lambda USE
129
+ headerValue.headers["x-project-env"] = process.env.APP_ENV;
130
+ if (downloadBytes) {
131
+ headerValue["responseType"] = "stream";
132
+ }
133
+ try {
134
+ let result = null;
135
+ if (!isRawJSON) {
136
+ if (requestDataType === "FORM_URL_ENCODED" || isUrlEncoded) {
137
+ data = qs.stringify(data);
138
+ drapcode_logger_1.logger.info("**17 Encoded data:", data, { label: projectId });
139
+ }
140
+ if (requestDataType === "NO_BODY_DATA")
141
+ data = {};
142
+ }
143
+ result = await makeAxiosCall(projectId, methodType, url, headerValue, data, timeout, wrapJsonDataInArray, awsSignPluginConfig);
144
+ drapcode_logger_1.logger.info(`result.headers: ${result?.headers}`, { label: projectId });
145
+ if (!result) {
146
+ const errorMessage = "No Response from Server";
147
+ return prepareReturnObject(errorMessage);
148
+ }
149
+ drapcode_logger_1.logger.info(`result.status: ${result?.status}`, { label: projectId });
150
+ deleteLocalFiles(isMultipart, toDeleteFiles);
151
+ return prepareReturnObject(result.data, result.status, true, result?.headers);
152
+ }
153
+ catch (error) {
154
+ deleteLocalFiles(isMultipart, toDeleteFiles);
155
+ const err = error;
156
+ let errData = null, errStatus = 400;
157
+ if (err.response) {
158
+ drapcode_logger_1.logger.info(`err.response.data: ${err.response.data ? JSON.stringify(err.response.data) : ""}`, {
159
+ label: projectId,
160
+ });
161
+ drapcode_logger_1.logger.info(`err.response.status: ${err.response.status}`, {
162
+ label: projectId,
163
+ });
164
+ drapcode_logger_1.logger.info(`err.response.headers: ${err.response.headers ? JSON.stringify(err.response.headers) : ""}`, {
165
+ label: projectId,
166
+ });
167
+ errData = err.response.data;
168
+ errStatus = err.response.status;
169
+ }
170
+ else if (err.request) {
171
+ errData = "No Response Received from the API";
172
+ drapcode_logger_1.logger.info(`err.request: ${err.request}`, { label: projectId });
173
+ }
174
+ else {
175
+ if (err.message.includes("ECONNABORTED")) {
176
+ errData = timeoutMessage || "No response received from the REST API";
177
+ }
178
+ else {
179
+ errData = err.message;
180
+ }
181
+ }
182
+ return prepareReturnObject(errData, errStatus);
183
+ }
259
184
  };
260
185
  exports.callCurlRequest = callCurlRequest;
261
- var deleteLocalFiles = function (isMultipart, toDeleteFiles) {
186
+ const deleteLocalFiles = (isMultipart, toDeleteFiles) => {
262
187
  if (isMultipart && toDeleteFiles) {
263
- toDeleteFiles.forEach(function (filePath) {
188
+ toDeleteFiles.forEach((filePath) => {
264
189
  console.log("==> TO DELETE FILES ARRAY filePath :>> ", filePath);
265
190
  fs.exists(filePath, function (exists) {
266
191
  if (exists) {
@@ -274,87 +199,70 @@ var deleteLocalFiles = function (isMultipart, toDeleteFiles) {
274
199
  });
275
200
  }
276
201
  };
277
- var prepareReturnObject = function (data, status, success, headers) {
278
- if (status === void 0) { status = 400; }
279
- if (success === void 0) { success = false; }
280
- if (headers === void 0) { headers = {}; }
202
+ const prepareReturnObject = (data, status = 400, success = false, headers = {}) => {
281
203
  return {
282
- data: data,
283
- status: status,
284
- success: success,
285
- headers: headers,
204
+ data,
205
+ status,
206
+ success,
207
+ headers,
286
208
  };
287
209
  };
288
- var makeAxiosCall = function (projectId, methodType, url, axiosConfig, data, timeout, wrapJsonDataInArray, awsSignPluginConfig) { return __awaiter(void 0, void 0, void 0, function () {
289
- var result, instance, dataArray_1, payload, urlObj_1, awsRes, error_2;
290
- return __generator(this, function (_a) {
291
- switch (_a.label) {
292
- case 0:
293
- axiosConfig = __assign({ url: url, method: methodType }, axiosConfig);
294
- result = "";
295
- instance = axios_1.default.create();
296
- instance.defaults.timeout = timeout * 1000;
297
- switch (methodType) {
298
- case "GET":
299
- axiosConfig["data"] = data ? data : {};
300
- break;
301
- case "POST":
302
- case "PUT":
303
- case "PATCH":
304
- if (wrapJsonDataInArray) {
305
- dataArray_1 = [];
306
- if (Object.keys(data) && Object.keys(data).length) {
307
- if (Object.keys(data)[0] === "0") {
308
- Object.keys(data).map(function (dataKey) {
309
- dataArray_1.push(data[dataKey]);
310
- });
311
- data = dataArray_1;
312
- }
313
- }
314
- }
315
- axiosConfig["data"] = data;
316
- break;
317
- case "DELETE":
318
- //Sending data object via axiosConfig
319
- if (data && Object.entries(data).length) {
320
- axiosConfig["data"] = __assign({}, data);
321
- }
322
- break;
323
- default:
324
- break;
325
- }
326
- _a.label = 1;
327
- case 1:
328
- _a.trys.push([1, 5, , 6]);
329
- if (!awsSignPluginConfig) return [3 /*break*/, 3];
330
- payload = JSON.stringify(data);
331
- axiosConfig = __assign(__assign({}, axiosConfig), { data: payload });
332
- if (axiosConfig.params) {
333
- urlObj_1 = new URL(axiosConfig.url);
334
- Object.entries(axiosConfig.params).forEach(function (_a) {
335
- var key = _a[0], value = _a[1];
336
- urlObj_1.searchParams.append(key, value);
337
- });
338
- axiosConfig.url = urlObj_1.toString();
210
+ const makeAxiosCall = async (projectId, methodType, url, axiosConfig, data, timeout, wrapJsonDataInArray, awsSignPluginConfig) => {
211
+ axiosConfig = { url, method: methodType, ...axiosConfig };
212
+ let result = "";
213
+ const instance = axios_1.default.create();
214
+ instance.defaults.timeout = timeout * 1000;
215
+ switch (methodType) {
216
+ case "GET":
217
+ axiosConfig["data"] = data ? data : {};
218
+ break;
219
+ case "POST":
220
+ case "PUT":
221
+ case "PATCH":
222
+ if (wrapJsonDataInArray) {
223
+ let dataArray = [];
224
+ if (Object.keys(data) && Object.keys(data).length) {
225
+ if (Object.keys(data)[0] === "0") {
226
+ Object.keys(data).map((dataKey) => {
227
+ dataArray.push(data[dataKey]);
228
+ });
229
+ data = dataArray;
230
+ }
339
231
  }
340
- return [4 /*yield*/, (0, util_1.getAwsSignature)(axiosConfig, awsSignPluginConfig)];
341
- case 2:
342
- awsRes = _a.sent();
343
- if (awsRes.error)
344
- return [2 /*return*/, awsRes.error];
345
- axiosConfig = __assign(__assign({}, awsRes.data), { data: payload });
346
- _a.label = 3;
347
- case 3:
348
- console.log("\n ==> Final axiosConfig for projectID: ".concat(projectId, ":>> "), axiosConfig);
349
- return [4 /*yield*/, (0, axios_1.default)(__assign({}, axiosConfig))];
350
- case 4:
351
- result = _a.sent();
352
- return [2 /*return*/, result];
353
- case 5:
354
- error_2 = _a.sent();
355
- console.log("\n ===error", error_2);
356
- return [2 /*return*/, error_2];
357
- case 6: return [2 /*return*/];
232
+ }
233
+ axiosConfig["data"] = data;
234
+ break;
235
+ case "DELETE":
236
+ //Sending data object via axiosConfig
237
+ if (data && Object.entries(data).length) {
238
+ axiosConfig["data"] = { ...data };
239
+ }
240
+ break;
241
+ default:
242
+ break;
243
+ }
244
+ try {
245
+ if (awsSignPluginConfig) {
246
+ const payload = JSON.stringify(data);
247
+ axiosConfig = { ...axiosConfig, data: payload };
248
+ if (axiosConfig.params) {
249
+ const urlObj = new URL(axiosConfig.url);
250
+ Object.entries(axiosConfig.params).forEach(([key, value]) => {
251
+ urlObj.searchParams.append(key, value);
252
+ });
253
+ axiosConfig.url = urlObj.toString();
254
+ }
255
+ const awsRes = await (0, util_1.getAwsSignature)(axiosConfig, awsSignPluginConfig);
256
+ if (awsRes.error)
257
+ return awsRes.error;
258
+ axiosConfig = { ...awsRes.data, data: payload };
358
259
  }
359
- });
360
- }); };
260
+ console.log(`\n ==> Final axiosConfig for projectID: ${projectId}:>> `, axiosConfig);
261
+ result = await (0, axios_1.default)({ ...axiosConfig });
262
+ return result;
263
+ }
264
+ catch (error) {
265
+ console.log("\n ===error", error);
266
+ return error;
267
+ }
268
+ };