|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var util = require('util'); |
| 4 | +var path = require('path'); |
| 5 | + |
| 6 | +module.exports = function (options) { |
| 7 | + var opts = util._extend({ |
| 8 | + indent: ' ' |
| 9 | + }, options); |
| 10 | + |
| 11 | + var code = ['var unirest = require("unirest");', null]; |
| 12 | + if(this.source.cookies.length){ |
| 13 | + code.push('var CookieJar = unirest.jar();'); |
| 14 | + var cookies = {}; |
| 15 | + var url = this.source.url; |
| 16 | + this.source.cookies.forEach(function(cookie){ |
| 17 | + code.push(util.format('CookieJar.add("%s=%s","%s")',encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), url)); |
| 18 | + }) |
| 19 | + code.push(null); |
| 20 | + } |
| 21 | + code.push(util.format('unirest.%s("%s")', this.source.method.toLowerCase(), this.source.url)); |
| 22 | + if (Object.keys(this.source.queryObj).length) { |
| 23 | + code.push(opts.indent + util.format('.query(%s)',JSON.stringify(this.source.queryObj))) |
| 24 | + } |
| 25 | + if(this.source.cookies.length){ |
| 26 | + code.push(opts.indent + '.jar(CookieJar)') |
| 27 | + } |
| 28 | + if (Object.keys(this.source.headersObj).length) { |
| 29 | + var self = this; |
| 30 | + var newHeadersObj = Object.keys(this.source.headersObj).reduce(function(finalHeader, headerName){ |
| 31 | + if(headerName !== 'Content-Type'){ |
| 32 | + finalHeader[headerName] = self.source.headersObj[headerName]; |
| 33 | + } |
| 34 | + return finalHeader; |
| 35 | + }, {}) |
| 36 | + if(Object.keys(newHeadersObj).length){ |
| 37 | + code.push(opts.indent + util.format('.headers(%s)',JSON.stringify(newHeadersObj))); |
| 38 | + } |
| 39 | + } |
| 40 | + if(this.source.postData.mimeType){ |
| 41 | + if(this.source.postData.mimeType !== 'application/octet-stream'){ |
| 42 | + code.push(opts.indent + util.format('.type("%s")',this.source.postData.mimeType)) |
| 43 | + } |
| 44 | + if(this.source.postData.mimeType === 'multipart/form-data'){ |
| 45 | + // not sure how unirest handles multipart |
| 46 | + } |
| 47 | + } |
| 48 | + if(this.source.postData.paramsObj.length){ |
| 49 | + code.push(opts.indent + util.format('.send(%s)', this.source.postData.paramsObj)); |
| 50 | + } |
| 51 | + code.push(opts.indent + '.end(function(response){') |
| 52 | + code.push(opts.indent + opts.indent + 'if (response.error) throw new Error(response.error);'); |
| 53 | + code.push(null); |
| 54 | + code.push(opts.indent+opts.indent+ 'console.log(reponse.body);'); |
| 55 | + code.push(opts.indent+'});'); |
| 56 | + code.push(null); |
| 57 | + |
| 58 | + return code.join('\n'); |
| 59 | +}; |
| 60 | + |
| 61 | +module.exports.info = { |
| 62 | + key: 'unirest', |
| 63 | + title: 'Unirest', |
| 64 | + link: 'https://github.com/request/request', |
| 65 | + description: 'Simplified HTTP request client.' |
| 66 | +}; |
0 commit comments