caccl-send-request 2.2.2 → 2.2.3

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 (2) hide show
  1. package/package.json +2 -2
  2. package/src/index.ts +31 -5
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "caccl-send-request",
3
- "version": "2.2.2",
3
+ "version": "2.2.3",
4
4
  "description": "The default request sender used throughout the CACCL project.",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./lib/index.d.ts",
@@ -36,7 +36,7 @@
36
36
  "typescript": "^4.5.5"
37
37
  },
38
38
  "dependencies": {
39
- "caccl-error": "^2.2.2",
39
+ "caccl-error": "^2.2.3",
40
40
  "qs": "^6.9.6"
41
41
  }
42
42
  }
package/src/index.ts CHANGED
@@ -53,8 +53,24 @@ const sendRequest = async (
53
53
  // Process method
54
54
  const method: ('GET' | 'POST' | 'PUT' | 'DELETE') = (opts.method || 'GET');
55
55
 
56
+ // Encode objects within params
57
+ let params: {
58
+ [k in string]: any
59
+ } | undefined;
60
+ if (opts.params) {
61
+ params = {};
62
+ Object.keys(opts.params).forEach((key) => {
63
+ const val = opts.params[key];
64
+ if (typeof val === 'object') {
65
+ params[key] = JSON.stringify(val);
66
+ } else {
67
+ params[key] = val;
68
+ }
69
+ });
70
+ }
71
+
56
72
  // Stringify parameters
57
- const stringifiedParams = qs.stringify(opts.params || {}, {
73
+ const stringifiedParams = qs.stringify(params || {}, {
58
74
  encodeValuesOnly: true,
59
75
  arrayFormat: 'brackets',
60
76
  });
@@ -74,12 +90,22 @@ const sendRequest = async (
74
90
  let data = null;
75
91
  if (!headers['Content-Type']) {
76
92
  // Form encoded
77
- headers['Content-Type'] = 'application/json';
93
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
78
94
  // Add data if applicable
79
95
  data = (method !== 'GET' ? stringifiedParams : null);
80
96
  } else {
81
97
  // JSON encode
82
- data = opts.params;
98
+ data = params;
99
+ }
100
+
101
+ // Encode data
102
+ let encodedData: URLSearchParams | string | undefined;
103
+ if (data) {
104
+ if (headers['Content-Type'] === 'application/x-www-form-urlencoded') {
105
+ encodedData = new URLSearchParams(params);
106
+ } else {
107
+ encodedData = JSON.stringify(data);
108
+ }
83
109
  }
84
110
 
85
111
  // Send request
@@ -91,8 +117,8 @@ const sendRequest = async (
91
117
  mode: 'cors',
92
118
  headers: headers ?? {},
93
119
  body: (
94
- (method !== 'GET' && data)
95
- ? JSON.stringify(data)
120
+ (method !== 'GET' && encodedData)
121
+ ? encodedData
96
122
  : undefined
97
123
  ),
98
124
  credentials: (