Last active
August 29, 2015 14:05
-
-
Save mlconnor/589db5828994aa957fee to your computer and use it in GitHub Desktop.
A quick first pass at turning request.js options object into a curl command. Much work needed here for escaping and edge cases.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function request2Curl(options) { | |
var tokens = ['curl', '-v', '-k', '-ssl3']; | |
if ( _.has(options, 'auth') ) { | |
if ( _.has(options.auth, 'user') ) { | |
tokens.push('--user', "'" + options.auth.user + ":" + options.auth.pass + "'"); | |
} | |
} | |
var isPost = _.has(options, 'method') && options.method.toLowerCase() == 'post'; | |
if ( isPost ) { | |
tokens.push('-X', 'POST'); | |
} | |
if ( _.has(options, 'headers') ) { | |
_.each(options.headers, function(value,key) { | |
tokens.push('-H', "'" + key + ':' + value + "'"); | |
}); | |
} | |
if ( _.has(options, 'json') ) { | |
tokens.push('-H', "'Content-Type:application/json'"); | |
if ( options.json !== true ) { | |
tokens.push('-d', "'" + JSON.stringify(options.json) + "'"); | |
} | |
} | |
if ( _.has(options, 'qs') ) { | |
var parsedUrl = url.parse(options.url); | |
if ( ! isPost ) { | |
if ( parsedUrl.query == null ) { | |
parsedUrl.query = options.qs; | |
} else { | |
parsedUrl.query = parsedUrl.query + '&' + querystring.encode(options.qs); | |
} | |
options.url = url.format(parsedUrl); | |
} | |
} | |
tokens.push("'" + options.url + "'"); | |
return tokens.join(" "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment