|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +var util = require('util'); |
| 4 | +var reducer = require('.,/../../reducer'); |
| 5 | + |
| 6 | +module.exports = function (options) { |
| 7 | + var opts = util._extend({ |
| 8 | + indent: ' ' |
| 9 | + }, options); |
| 10 | + |
| 11 | + var code = []; |
| 12 | + |
| 13 | + var reqOpts = { |
| 14 | + method: this.source.method, |
| 15 | + hostname: this.source.uriObj.hostname, |
| 16 | + port: this.source.uriObj.port, |
| 17 | + path: this.source.uriObj.path, |
| 18 | + headers: this.source.headersObj |
| 19 | + }; |
| 20 | + |
| 21 | + // construct cookies argument |
| 22 | + var cookies = this.source.cookies.map(function (cookie) { |
| 23 | + return encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value); |
| 24 | + }); |
| 25 | + |
| 26 | + if (cookies.length) { |
| 27 | + reqOpts.headers.Cookie = cookies.join('; '); |
| 28 | + } |
| 29 | + |
| 30 | + code.push('var request = require("request");'); |
| 31 | + |
| 32 | + if (!this.source.postData.text && this.source.postData.params) { |
| 33 | + code.push('var querystring = require("querystring");'); |
| 34 | + } |
| 35 | + |
| 36 | + code.push(null); |
| 37 | + |
| 38 | + code.push(util.format('var options = %s;', JSON.stringify(reqOpts, null, opts.indent))); |
| 39 | + |
| 40 | + code.push(null); |
| 41 | + |
| 42 | + code.push('var req = http.request(options, function (res) {'); |
| 43 | + |
| 44 | + code.push(opts.indent + 'var chunks = [];'); |
| 45 | + |
| 46 | + code.push(null); |
| 47 | + |
| 48 | + code.push(opts.indent + 'res.on("data", function (chunk) {'); |
| 49 | + code.push(opts.indent + opts.indent + 'chunks.push(chunk);'); |
| 50 | + code.push(opts.indent + '});'); |
| 51 | + |
| 52 | + code.push(null); |
| 53 | + |
| 54 | + code.push(opts.indent + 'res.on("end", function () {'); |
| 55 | + code.push(opts.indent + opts.indent + 'var body = Buffer.concat(chunks);'); |
| 56 | + code.push(opts.indent + '});'); |
| 57 | + code.push('});'); |
| 58 | + |
| 59 | + code.push(null); |
| 60 | + |
| 61 | + if (this.source.postData.text) { |
| 62 | + code.push(util.format('req.write(%s);', JSON.stringify(this.source.postData.text))); |
| 63 | + } |
| 64 | + |
| 65 | + if (!this.source.postData.text && this.source.postData.params) { |
| 66 | + var postData = this.source.postData.params.reduce(reducer, {}); |
| 67 | + |
| 68 | + code.push(util.format('var postData = querystring.stringify(%s);', JSON.stringify(postData))); |
| 69 | + code.push(util.format('req.write(postData);')); |
| 70 | + } |
| 71 | + |
| 72 | + code.push('req.end();'); |
| 73 | + |
| 74 | + return code.join('\n'); |
| 75 | +}; |
| 76 | + |
| 77 | +module.exports.info = { |
| 78 | + key: 'native', |
| 79 | + title: 'HTTP', |
| 80 | + link: 'http://nodejs.org/api/http.html#http_http_request_options_callback', |
| 81 | + description: 'Node.js native HTTP interface' |
| 82 | +}; |
0 commit comments