diff --git a/src/helpers/headers.js b/src/helpers/headers.js index c37701adf..7a37e8526 100644 --- a/src/helpers/headers.js +++ b/src/helpers/headers.js @@ -35,5 +35,23 @@ module.exports = { */ hasHeader: (headers, name) => { return Boolean(Object.keys(headers).find(k => k.toLowerCase() === name.toLowerCase())) + }, + + /** + * Determines if a given mimetype is JSON, or a variant of such. + * + * @param {string}} mimeType + * @returns {boolean} + */ + isMimeTypeJson: (mimeType) => { + return [ + 'application/json', + 'application/x-json', + 'text/json', + 'text/x-json', + '+json' + ].some(function (type) { + return mimeType.indexOf(type) > -1 + }) } } diff --git a/src/targets/shell/curl.js b/src/targets/shell/curl.js index 3cde6bb5a..2b14b2fbc 100644 --- a/src/targets/shell/curl.js +++ b/src/targets/shell/curl.js @@ -11,7 +11,7 @@ 'use strict' const util = require('util') -const helpers = require('../../helpers/shell') +const helpers = require('./helpers') const headerHelpers = require('../../helpers/headers') const CodeBuilder = require('../../helpers/code-builder') @@ -100,10 +100,38 @@ module.exports = function (source, options) { default: // raw request body if (source.postData.text) { - code.push( - '%s %s', opts.binary ? '--data-binary' : (opts.short ? '-d' : '--data'), - helpers.quote(source.postData.text) - ) + let builtPayload = false + + // If we're dealing with a JSON variant, and our payload is JSON let's make it look a little nicer. + if (headerHelpers.isMimeTypeJson(source.postData.mimeType)) { + // If our postData is less than 20 characters, let's keep it all on one line so as to not make the snippet + // overly lengthy. + if (source.postData.text.length > 20) { + try { + const jsonPayload = JSON.parse(source.postData.text) + + // If the JSON object has a single quote we should prepare it inside of a HEREDOC because the single + // quote in something like `string's` can't be escaped when used with `--data`. + // + // Basically this boils down to `--data @- < 0 ? '%s @- <