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