|
| 1 | +const _ = require('./lodash'); |
| 2 | + |
1 | 3 | var self = module.exports = { |
2 | 4 | /** |
3 | 5 | * sanitizes input string by handling escape characters eg: converts '''' to '\'\'', (" to \" and \ to \\ ) |
@@ -199,5 +201,78 @@ var self = module.exports = { |
199 | 201 | contentType: contentType |
200 | 202 | }); |
201 | 203 | } |
| 204 | + }, |
| 205 | + |
| 206 | + /** |
| 207 | + * @param {Object} body |
| 208 | + * @returns {boolean} |
| 209 | + * |
| 210 | + * Determines if a request body is actually empty. |
| 211 | + * This is needed because body.isEmpty() returns false for formdata |
| 212 | + * and urlencoded when they contain only disabled params which will not |
| 213 | + * be a part of the curl request. |
| 214 | + */ |
| 215 | + isBodyEmpty (body) { |
| 216 | + if (!body) { |
| 217 | + return true; |
| 218 | + } |
| 219 | + |
| 220 | + if (body.isEmpty()) { |
| 221 | + return true; |
| 222 | + } |
| 223 | + |
| 224 | + if (body.mode === 'formdata' || body.mode === 'urlencoded') { |
| 225 | + let memberCount = 0; |
| 226 | + body[body.mode] && body[body.mode].members && body[body.mode].members.forEach((param) => { |
| 227 | + if (!param.disabled) { |
| 228 | + memberCount += 1; |
| 229 | + } |
| 230 | + }); |
| 231 | + |
| 232 | + return memberCount === 0; |
| 233 | + } |
| 234 | + |
| 235 | + return false; |
| 236 | + }, |
| 237 | + |
| 238 | + /** |
| 239 | + * Decide whether we should add the HTTP method explicitly to the cURL command. |
| 240 | + * |
| 241 | + * @param {Object} request |
| 242 | + * @param {Object} options |
| 243 | + * |
| 244 | + * @returns {Boolean} |
| 245 | + */ |
| 246 | + shouldAddHttpMethod: function (request, options) { |
| 247 | + const followRedirect = _.get(request, 'protocolProfileBehavior.followRedirects', options.followRedirect), |
| 248 | + followOriginalHttpMethod = |
| 249 | + _.get(request, 'protocolProfileBehavior.followOriginalHttpMethod', options.followOriginalHttpMethod), |
| 250 | + disableBodyPruning = _.get(request, 'protocolProfileBehavior.disableBodyPruning', true), |
| 251 | + isBodyEmpty = self.isBodyEmpty(request.body); |
| 252 | + |
| 253 | + if (followRedirect && followOriginalHttpMethod) { |
| 254 | + return true; |
| 255 | + } |
| 256 | + |
| 257 | + switch (request.method) { |
| 258 | + case 'HEAD': |
| 259 | + return false; |
| 260 | + case 'GET': |
| 261 | + // disableBodyPruning will generally not be present in the request |
| 262 | + // the only time it will be present, its value will be _false_ |
| 263 | + // i.e. the user wants to prune the request body despite it being present |
| 264 | + if (!isBodyEmpty && disableBodyPruning) { |
| 265 | + return true; |
| 266 | + } |
| 267 | + |
| 268 | + return false; |
| 269 | + case 'POST': |
| 270 | + return isBodyEmpty; |
| 271 | + case 'DELETE': |
| 272 | + case 'PUT': |
| 273 | + case 'PATCH': |
| 274 | + default: |
| 275 | + return true; |
| 276 | + } |
202 | 277 | } |
203 | 278 | }; |
0 commit comments