|
| 1 | +'use strict' |
| 2 | + |
| 3 | +var util = require('util') |
| 4 | + |
| 5 | +module.exports = function (source, options) { |
| 6 | + var self = this |
| 7 | + var code = [] |
| 8 | + code.push('require \'uri\'') |
| 9 | + code.push('require \'net/http\'') |
| 10 | + code.push(null) |
| 11 | + |
| 12 | + // To support custom methods we check for the supported methods |
| 13 | + // and if doesn't exist then we build a custom class for it |
| 14 | + var method = source.method.toUpperCase() |
| 15 | + var methods = ['GET', 'POST', 'HEAD', 'DELETE', 'PATCH', 'PUT', 'OPTIONS', 'COPY', 'LOCK', 'UNLOCK', 'MOVE', 'TRACE'] |
| 16 | + var capMethod = method.charAt(0) + method.substring(1).toLowerCase() |
| 17 | + if (methods.indexOf(method) < 0) { |
| 18 | + code.push('class Net::HTTP::%s < Net::HTTPRequest') |
| 19 | + code.push(util.format('class Net::HTTP::%s < Net::HTTPRequest', capMethod)) |
| 20 | + code.push(util.format(' METHOD = \'%s\'', method.toUpperCase())) |
| 21 | + code.push(util.format(' REQUEST_HAS_BODY = \'%s\'', self.source.postData.text ? 'true' : 'false')) |
| 22 | + code.push(' RESPONSE_HAS_BODY = true') |
| 23 | + code.push('end') |
| 24 | + code.push(null) |
| 25 | + } |
| 26 | + |
| 27 | + code.push(util.format('url = URI("%s")', source.fullUrl)) |
| 28 | + |
| 29 | + code.push(null) |
| 30 | + |
| 31 | + code.push('conn = Net::HTTP.new(url.host, url.port)') |
| 32 | + |
| 33 | + if (source.uriObj.protocol === 'https:') { |
| 34 | + code.push('http.use_ssl = true') |
| 35 | + code.push('http.verify_mode = OpenSSL::SSL::VERIFY_NONE') |
| 36 | + } |
| 37 | + |
| 38 | + code.push(null) |
| 39 | + |
| 40 | + code.push(util.format('request = Net::HTTP::%s.new(url)', capMethod)) |
| 41 | + |
| 42 | + var headers = Object.keys(self.source.allHeaders) |
| 43 | + if (headers.length) { |
| 44 | + headers.map(function (key) { |
| 45 | + code.push(util.format('request["%s"] = \'%s\'', key, self.source.allHeaders[key])) |
| 46 | + }) |
| 47 | + } |
| 48 | + |
| 49 | + if (self.source.postData.text) { |
| 50 | + code.push(util.format('request.body = %s', JSON.stringify(self.source.postData.text))) |
| 51 | + } |
| 52 | + |
| 53 | + code.push(null) |
| 54 | + |
| 55 | + code.push('response = conn.request(request)') |
| 56 | + code.push('puts response.read_body') |
| 57 | + |
| 58 | + return code.join('\n') |
| 59 | +} |
| 60 | + |
| 61 | +module.exports.info = { |
| 62 | + key: 'native', |
| 63 | + title: 'net::http', |
| 64 | + link: 'http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTPGenericRequest.html', |
| 65 | + description: 'Ruby request client' |
| 66 | +} |
0 commit comments