|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * HTTP code snippet generator for native Crystal |
| 4 | + * |
| 5 | + * @author |
| 6 | + * @yanecc |
| 7 | + * |
| 8 | + * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. |
| 9 | + */ |
| 10 | + |
| 11 | +const CodeBuilder = require('../../helpers/code-builder') |
| 12 | + |
| 13 | +const { escape } = require('../../helpers/format') |
| 14 | + |
| 15 | +module.exports = function ({ method: rawMethod, fullUrl, postData, allHeaders }, options = {}) { |
| 16 | + const { insecureSkipVerify = false } = options |
| 17 | + |
| 18 | + const code = new CodeBuilder() |
| 19 | + |
| 20 | + code.push('require "http/client"') |
| 21 | + |
| 22 | + code.blank() |
| 23 | + |
| 24 | + code.push(`url = "${fullUrl}"`) |
| 25 | + |
| 26 | + const headers = Object.keys(allHeaders) |
| 27 | + if (headers.length) { |
| 28 | + code.push('headers = HTTP::Headers{') |
| 29 | + headers.forEach(key => { |
| 30 | + code.push(` "${key}" => "${escape(allHeaders[key])}"`) |
| 31 | + }) |
| 32 | + code.push('}') |
| 33 | + } |
| 34 | + |
| 35 | + if (postData.text) { |
| 36 | + code.push(`reqBody = ${JSON.stringify(postData.text)}`) |
| 37 | + } |
| 38 | + |
| 39 | + code.blank() |
| 40 | + |
| 41 | + const method = rawMethod.toUpperCase() |
| 42 | + const methods = ['GET', 'POST', 'HEAD', 'DELETE', 'PATCH', 'PUT', 'OPTIONS'] |
| 43 | + |
| 44 | + const headersContext = headers.length ? ', headers: headers' : '' |
| 45 | + const bodyContext = postData.text ? ', body: reqBody' : '' |
| 46 | + const sslContext = insecureSkipVerify ? ', tls: OpenSSL::SSL::Context::Client.insecure' : '' |
| 47 | + |
| 48 | + if (methods.includes(method)) { |
| 49 | + code.push( |
| 50 | + `response = HTTP::Client.${method.toLowerCase()} url${headersContext}${bodyContext}${sslContext}` |
| 51 | + ) |
| 52 | + } else { |
| 53 | + code.push( |
| 54 | + `response = HTTP::Client.exec "${method}", url${headersContext}${bodyContext}${sslContext}` |
| 55 | + ) |
| 56 | + } |
| 57 | + |
| 58 | + code.push('puts response.body') |
| 59 | + |
| 60 | + return code.join() |
| 61 | +} |
| 62 | + |
| 63 | +module.exports.info = { |
| 64 | + key: 'native', |
| 65 | + title: 'http::client', |
| 66 | + link: 'https://crystal-lang.org/api/master/HTTP/Client.html', |
| 67 | + description: 'Crystal HTTP client' |
| 68 | +} |
0 commit comments