From 520ac8ede5b36d814902ac4083973c20674004d3 Mon Sep 17 00:00:00 2001 From: Deepanshu Dhruw Date: Tue, 30 Nov 2021 07:46:45 +0530 Subject: [PATCH] fix: code generators (#1985) Co-authored-by: liyasthomas --- .../helpers/codegen/generators/c-libcurl.js | 28 +++++---- .../codegen/generators/cs-restsharp.js | 19 +++---- .../helpers/codegen/generators/curl.js | 6 +- .../helpers/codegen/generators/go-native.js | 31 +++++----- .../helpers/codegen/generators/java-okhttp.js | 26 ++++++--- .../codegen/generators/java-unirest.js | 23 ++++---- .../codegen/generators/javascript-fetch.js | 24 ++++---- .../codegen/generators/javascript-jquery.js | 28 ++++----- .../codegen/generators/javascript-xhr.js | 17 +++--- .../codegen/generators/nodejs-axios.js | 34 +++++++---- .../codegen/generators/nodejs-native.js | 11 +--- .../codegen/generators/nodejs-request.js | 43 +++++++------- .../codegen/generators/nodejs-unirest.js | 46 +++++++-------- .../helpers/codegen/generators/php-curl.js | 48 ++++++++-------- .../generators/powershell-restmethod.js | 22 ++++--- .../codegen/generators/python-http-client.js | 33 ++++++----- .../codegen/generators/python-requests.js | 57 ++++++++++--------- .../codegen/generators/ruby-net-http.js | 13 ++--- .../codegen/generators/salesforce-apex.js | 20 +++---- .../codegen/generators/shell-httpie.js | 11 +--- .../helpers/codegen/generators/shell-wget.js | 8 +-- 21 files changed, 285 insertions(+), 263 deletions(-) diff --git a/packages/hoppscotch-app/helpers/codegen/generators/c-libcurl.js b/packages/hoppscotch-app/helpers/codegen/generators/c-libcurl.js index 1d537760..7cb2b598 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/c-libcurl.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/c-libcurl.js @@ -28,6 +28,7 @@ export const CLibcurlCodegen = { ) requestString.push(`struct curl_slist *headers = NULL;`) + // append header attributes if (headers) { headers.forEach(({ key, value }) => { if (key) @@ -50,22 +51,27 @@ export const CLibcurlCodegen = { ) } + // set headers + if (headers?.length) { + requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);") + } + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody - if (contentType.includes("x-www-form-urlencoded")) { + if (contentType && contentType.includes("x-www-form-urlencoded")) { requestBody = `"${requestBody}"` - } else requestBody = JSON.stringify(requestBody) + } else { + requestBody = requestBody ? JSON.stringify(requestBody) : null + } - requestString.push( - `headers = curl_slist_append(headers, "Content-Type: ${contentType}");` - ) - requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);") - requestString.push( - `curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${requestBody});` - ) - } else - requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);") + // set request-body + if (requestBody) { + requestString.push( + `curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${requestBody});` + ) + } + } requestString.push(`CURLcode ret = curl_easy_perform(hnd);`) return requestString.join("\n") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/cs-restsharp.js b/packages/hoppscotch-app/helpers/codegen/generators/cs-restsharp.js index c3452fac..597deaa7 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/cs-restsharp.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/cs-restsharp.js @@ -23,7 +23,9 @@ export const CsRestsharpCodegen = { // initial request setup let requestBody = rawInput ? rawParams : rawRequestBody - requestBody = requestBody.replace(/"/g, '""') // escape quotes for C# verbatim string compatibility + if (requestBody) { + requestBody = requestBody.replace(/"/g, '""') // escape quotes for C# verbatim string compatibility + } // prepare data let requestDataFormat @@ -62,13 +64,6 @@ export const CsRestsharpCodegen = { ) } - // content type - if (contentType) { - requestString.push( - `request.AddHeader("Content-Type", "${contentType}");\n` - ) - } - // custom headers if (headers) { headers.forEach(({ key, value }) => { @@ -81,7 +76,7 @@ export const CsRestsharpCodegen = { requestString.push(`\n`) // set body - if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) { requestString.push( `request.AddParameter("${requestContentType}", @"${requestBody}", ParameterType.RequestBody);\n\n` ) @@ -89,7 +84,11 @@ export const CsRestsharpCodegen = { // process const verb = verbs.find((v) => v.verb === method) - requestString.push(`var response = client.${verb.csMethod}(request);\n\n`) + if (verb) { + requestString.push(`var response = client.${verb.csMethod}(request);\n\n`) + } else { + return "" + } // analyse result requestString.push( diff --git a/packages/hoppscotch-app/helpers/codegen/generators/curl.js b/packages/hoppscotch-app/helpers/codegen/generators/curl.js index 2b7e18d1..41cb7918 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/curl.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/curl.js @@ -14,7 +14,6 @@ export const CurlCodegen = { rawInput, rawParams, rawRequestBody, - contentType, headers, }) => { const requestString = [] @@ -36,8 +35,9 @@ export const CurlCodegen = { }) } if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { - const requestBody = rawInput ? rawParams : rawRequestBody - requestString.push(` -H 'Content-Type: ${contentType}; charset=utf-8'`) + let requestBody = rawInput ? rawParams : rawRequestBody + requestBody = requestBody || "" + requestString.push(` -d '${requestBody}'`) } return requestString.join(" \\\n") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/go-native.js b/packages/hoppscotch-app/helpers/codegen/generators/go-native.js index 3339b265..8f5a6917 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/go-native.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/go-native.js @@ -23,23 +23,28 @@ export const GoNativeCodegen = { let genHeaders = [] // initial request setup const requestBody = rawInput ? rawParams : rawRequestBody - if (method === "GET") { - requestString.push( - `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}")\n` - ) - } + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { - genHeaders.push(`req.Header.Set("Content-Type", "${contentType}")\n`) - if (isJSONContentType(contentType)) { - requestString.push(`var reqBody = []byte(\`${requestBody}\`)\n\n`) + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestString.push(`var reqBody = []byte(\`${requestBody}\`)\n\n`) + requestString.push( + `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", bytes.NewBuffer(reqBody))\n` + ) + } else if (contentType.includes("x-www-form-urlencoded")) { + requestString.push( + `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", strings.NewReader("${requestBody}"))\n` + ) + } + } else { requestString.push( - `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", bytes.NewBuffer(reqBody))\n` - ) - } else if (contentType.includes("x-www-form-urlencoded")) { - requestString.push( - `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", strings.NewReader("${requestBody}"))\n` + `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", nil)\n` ) } + } else { + requestString.push( + `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", nil)\n` + ) } // headers diff --git a/packages/hoppscotch-app/helpers/codegen/generators/java-okhttp.js b/packages/hoppscotch-app/helpers/codegen/generators/java-okhttp.js index 2225c406..1bec7ef0 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/java-okhttp.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/java-okhttp.js @@ -26,16 +26,26 @@ export const JavaOkhttpCodegen = { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody - if (contentType.includes("x-www-form-urlencoded")) { + if (contentType && contentType.includes("x-www-form-urlencoded")) { requestBody = `"${requestBody}"` - } else requestBody = JSON.stringify(requestBody) + } else { + requestBody = requestBody ? JSON.stringify(requestBody) : null + } - requestString.push( - `MediaType mediaType = MediaType.parse("${contentType}");` - ) - requestString.push( - `RequestBody body = RequestBody.create(mediaType,${requestBody});` - ) + if (contentType) { + requestString.push( + `MediaType mediaType = MediaType.parse("${contentType}");` + ) + } + if (requestBody) { + requestString.push( + `RequestBody body = RequestBody.create(mediaType,${requestBody});` + ) + } else { + requestString.push( + "RequestBody body = RequestBody.create(null, new byte[0]);" + ) + } } requestString.push("Request request = new Request.Builder()") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/java-unirest.js b/packages/hoppscotch-app/helpers/codegen/generators/java-unirest.js index c257c76e..bb696d6e 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/java-unirest.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/java-unirest.js @@ -31,8 +31,9 @@ export const JavaUnirestCodegen = { ] // create client and request const verb = verbs.find((v) => v.verb === method) + const unirestMethod = verb.unirestMethod || "get" requestString.push( - `HttpResponse response = Unirest.${verb.unirestMethod}("${url}${pathName}?${queryString}")\n` + `HttpResponse response = Unirest.${unirestMethod}("${url}${pathName}?${queryString}")\n` ) if (auth === "Basic Auth") { const basic = `${httpUser}:${httpPassword}` @@ -52,21 +53,21 @@ export const JavaUnirestCodegen = { } }) } - if (contentType) { - requestString.push(`.header("Content-Type", "${contentType}")\n`) - } // set body if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { - if (contentType.includes("x-www-form-urlencoded")) { - requestBody = `"${requestBody}"` - } else { - requestBody = JSON.stringify(requestBody) + if (contentType && requestBody) { + if (contentType.includes("x-www-form-urlencoded")) { + requestBody = `"${requestBody}"` + } else { + requestBody = JSON.stringify(requestBody) + } + } + if (requestBody) { + requestString.push(`.body(${requestBody})\n`) } - - requestString.push(`.body(${requestBody})`) } - requestString.push(`\n.asString();\n`) + requestString.push(`.asString();\n`) return requestString.join("") }, } diff --git a/packages/hoppscotch-app/helpers/codegen/generators/javascript-fetch.js b/packages/hoppscotch-app/helpers/codegen/generators/javascript-fetch.js index 7804e8d2..665cd6d1 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/javascript-fetch.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/javascript-fetch.js @@ -35,14 +35,18 @@ export const JavascriptFetchCodegen = { } if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody - if (isJSONContentType(contentType)) { - requestBody = `JSON.stringify(${requestBody})` - } else if (contentType.includes("x-www-form-urlencoded")) { - requestBody = `"${requestBody}"` + + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestBody = `JSON.stringify(${requestBody})` + } else if (contentType.includes("x-www-form-urlencoded")) { + requestBody = `"${requestBody}"` + } } - requestString.push(` body: ${requestBody},\n`) - genHeaders.push(` "Content-Type": "${contentType}; charset=utf-8",\n`) + if (requestBody) { + requestString.push(` body: ${requestBody},\n`) + } } if (headers) { headers.forEach(({ key, value }) => { @@ -50,13 +54,11 @@ export const JavascriptFetchCodegen = { }) } genHeaders = genHeaders.join("").slice(0, -2) - requestString.push(` headers: {\n${genHeaders}\n },\n`) + if (genHeaders) { + requestString.push(` headers: {\n${genHeaders}\n },\n`) + } requestString.push(' credentials: "same-origin"\n') requestString.push("}).then(function(response) {\n") - requestString.push(" response.status\n") - requestString.push(" response.statusText\n") - requestString.push(" response.headers\n") - requestString.push(" response.url\n\n") requestString.push(" return response.text()\n") requestString.push("}).catch(function(e) {\n") requestString.push(" console.error(e)\n") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/javascript-jquery.js b/packages/hoppscotch-app/helpers/codegen/generators/javascript-jquery.js index b2ca1c0b..6626fc2c 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/javascript-jquery.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/javascript-jquery.js @@ -13,8 +13,8 @@ export const JavascriptJqueryCodegen = { method, rawInput, rawParams, - rawRequestBody, contentType, + rawRequestBody, headers, }) => { const requestString = [] @@ -24,10 +24,15 @@ export const JavascriptJqueryCodegen = { `jQuery.ajax({\n url: "${url}${pathName}?${queryString}"` ) requestString.push(`,\n method: "${method.toUpperCase()}"`) - const requestBody = rawInput ? rawParams : rawRequestBody + let requestBody = rawInput ? rawParams : rawRequestBody - if (requestBody.length !== 0) { - requestString.push(`,\n body: ${requestBody}`) + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if (contentType && contentType.includes("x-www-form-urlencoded")) { + requestBody = `"${requestBody}"` + } else { + requestBody = requestBody.replaceAll("}", " }") + } + requestString.push(`,\n data: ${requestBody}`) } if (headers) { headers.forEach(({ key, value }) => { @@ -35,11 +40,6 @@ export const JavascriptJqueryCodegen = { }) } - if (contentType) { - genHeaders.push(` "Content-Type": "${contentType}; charset=utf-8",\n`) - requestString.push(`,\n contentType: "${contentType}; charset=utf-8"`) - } - if (auth === "Basic Auth") { const basic = `${httpUser}:${httpPassword}` genHeaders.push( @@ -50,10 +50,12 @@ export const JavascriptJqueryCodegen = { } else if (auth === "Bearer Token" || auth === "OAuth 2.0") { genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`) } - requestString.push( - `,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n})` - ) - requestString.push(".then(response => {\n") + if (genHeaders.length > 0) { + requestString.push( + `,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }` + ) + } + requestString.push("\n}).then(response => {\n") requestString.push(" console.log(response);\n") requestString.push("})") requestString.push(".catch(e => {\n") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/javascript-xhr.js b/packages/hoppscotch-app/helpers/codegen/generators/javascript-xhr.js index 3c752d05..63e1a8f1 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/javascript-xhr.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/javascript-xhr.js @@ -21,6 +21,9 @@ export const JavascriptXhrCodegen = { }) => { const requestString = [] requestString.push("const xhr = new XMLHttpRequest()") + requestString.push(`xhr.addEventListener("readystatechange", function() {`) + requestString.push(` if(this.readyState === 4) {`) + requestString.push(` console.log(this.responseText)\n }\n})`) const user = auth === "Basic Auth" ? `'${httpUser}'` : null const password = auth === "Basic Auth" ? `'${httpPassword}'` : null @@ -40,14 +43,14 @@ export const JavascriptXhrCodegen = { } if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody - if (isJSONContentType(contentType)) { - requestBody = `JSON.stringify(${requestBody})` - } else if (contentType.includes("x-www-form-urlencoded")) { - requestBody = `"${requestBody}"` + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestBody = `JSON.stringify(${requestBody})` + } else if (contentType.includes("x-www-form-urlencoded")) { + requestBody = `"${requestBody}"` + } } - requestString.push( - `xhr.setRequestHeader('Content-Type', '${contentType}; charset=utf-8')` - ) + requestBody = requestBody || "" requestString.push(`xhr.send(${requestBody})`) } else { requestString.push("xhr.send()") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-axios.js b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-axios.js index 349e2d25..325d6d0f 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-axios.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-axios.js @@ -19,22 +19,31 @@ export const NodejsAxiosCodegen = { }) => { const requestString = [] const genHeaders = [] - const requestBody = rawInput ? rawParams : rawRequestBody + let requestBody = rawInput ? rawParams : rawRequestBody + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if ( + contentType && + contentType.includes("x-www-form-urlencoded") && + requestBody + ) { + requestString.push( + `var params = new URLSearchParams("${requestBody}")\n` + ) + requestBody = "params" + } + } requestString.push( `axios.${method.toLowerCase()}('${url}${pathName}?${queryString}'` ) - if (requestBody.length !== 0) { + if (requestBody && requestBody.length !== 0) { requestString.push(", ") } if (headers) { headers.forEach(({ key, value }) => { - if (key) genHeaders.push(` "${key}": "${value}",\n`) + if (key) genHeaders.push(`\n "${key}": "${value}",`) }) } - if (contentType) { - genHeaders.push(`"Content-Type": "${contentType}; charset=utf-8",\n`) - } if (auth === "Basic Auth") { const basic = `${httpUser}:${httpPassword}` genHeaders.push( @@ -45,10 +54,15 @@ export const NodejsAxiosCodegen = { } else if (auth === "Bearer Token" || auth === "OAuth 2.0") { genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`) } - requestString.push( - `${requestBody},{ \n headers : {${genHeaders.join("").slice(0, -2)}}\n})` - ) - requestString.push(".then(response => {\n") + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + requestString.push(`${requestBody},`) + } + if (genHeaders.length > 0) { + requestString.push( + `{ \n headers : {${genHeaders.join("").slice(0, -1)}\n }\n}` + ) + } + requestString.push(").then(response => {\n") requestString.push(" console.log(response);\n") requestString.push("})") requestString.push(".catch(e => {\n") diff --git a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-native.js b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-native.js index cc551cca..e4d75f11 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-native.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-native.js @@ -43,16 +43,11 @@ export const NodejsNativeCodegen = { let requestBody if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { requestBody = rawInput ? rawParams : rawRequestBody - if (isJSONContentType(contentType)) { + if (isJSONContentType(contentType) && requestBody) { requestBody = `JSON.stringify(${requestBody})` - } else { + } else if (requestBody) { requestBody = `\`${requestBody}\`` } - if (contentType) { - genHeaders.push( - ` "Content-Type": "${contentType}; charset=utf-8",\n` - ) - } } if (headers) { @@ -62,7 +57,7 @@ export const NodejsNativeCodegen = { } if (genHeaders.length > 0 || headers.length > 0) { requestString.push( - ` headers: {\n${genHeaders.join("").slice(0, -2)}\n }` + ` headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n` ) } requestString.push(`};\n\n`) diff --git a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-request.js b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-request.js index cbdf218a..6e8ee992 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-request.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-request.js @@ -40,31 +40,30 @@ export const NodejsRequestCodegen = { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody let reqBodyType = "formData" - if (isJSONContentType(contentType)) { - requestBody = `JSON.stringify(${requestBody})` - reqBodyType = "body" - } else if (contentType.includes("x-www-form-urlencoded")) { - const formData = [] - if (requestBody.includes("=")) { - requestBody.split("&").forEach((rq) => { - const [key, val] = rq.split("=") - formData.push(`"${key}": "${val}"`) - }) + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestBody = `JSON.stringify(${requestBody})` + reqBodyType = "body" + } else if (contentType.includes("x-www-form-urlencoded")) { + const formData = [] + if (requestBody.includes("=")) { + requestBody.split("&").forEach((rq) => { + const [key, val] = rq.split("=") + formData.push(`"${key}": "${val}"`) + }) + } + if (formData.length) { + requestBody = `{${formData.join(", ")}}` + } + reqBodyType = "form" + } else if (contentType.includes("application/xml")) { + requestBody = `\`${requestBody}\`` + reqBodyType = "body" } - if (formData.length) { - requestBody = `{${formData.join(", ")}}` - } - reqBodyType = "form" - } else if (contentType.includes("application/xml")) { - requestBody = `\`${requestBody}\`` - reqBodyType = "body" } - if (contentType) { - genHeaders.push( - ` "Content-Type": "${contentType}; charset=utf-8",\n` - ) + if (requestBody) { + requestString.push(`,\n ${reqBodyType}: ${requestBody}`) } - requestString.push(`,\n ${reqBodyType}: ${requestBody}`) } if (headers.length > 0) { diff --git a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-unirest.js b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-unirest.js index dabab498..f533b52a 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/nodejs-unirest.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/nodejs-unirest.js @@ -42,31 +42,30 @@ export const NodejsUnirestCodegen = { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody let reqBodyType = "formData" - if (isJSONContentType(contentType)) { - requestBody = `\`${requestBody}\`` - reqBodyType = "send" - } else if (contentType.includes("x-www-form-urlencoded")) { - const formData = [] - if (requestBody.includes("=")) { - requestBody.split("&").forEach((rq) => { - const [key, val] = rq.split("=") - formData.push(`"${key}": "${val}"`) - }) + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestBody = `\`${requestBody}\`` + reqBodyType = "send" + } else if (contentType.includes("x-www-form-urlencoded")) { + const formData = [] + if (requestBody.includes("=")) { + requestBody.split("&").forEach((rq) => { + const [key, val] = rq.split("=") + formData.push(`"${key}": "${val}"`) + }) + } + if (formData.length) { + requestBody = `{${formData.join(", ")}}` + } + reqBodyType = "send" + } else if (contentType.includes("application/xml")) { + requestBody = `\`${requestBody}\`` + reqBodyType = "send" } - if (formData.length) { - requestBody = `{${formData.join(", ")}}` - } - reqBodyType = "send" - } else if (contentType.includes("application/xml")) { - requestBody = `\`${requestBody}\`` - reqBodyType = "send" } - if (contentType) { - genHeaders.push( - ` "Content-Type": "${contentType}; charset=utf-8",\n` - ) + if (requestBody) { + requestString.push(`\n.${reqBodyType}( ${requestBody})`) } - requestString.push(`.\n ${reqBodyType}( ${requestBody})`) } if (headers.length > 0) { @@ -76,11 +75,10 @@ export const NodejsUnirestCodegen = { } if (genHeaders.length > 0 || headers.length > 0) { requestString.push( - `.\n headers({\n${genHeaders.join("").slice(0, -2)}\n }` + `\n.headers({\n${genHeaders.join("").slice(0, -2)}\n })` ) } - requestString.push(`\n)`) requestString.push(`\n.end(function (res) {\n`) requestString.push(` if (res.error) throw new Error(res.error);\n`) requestString.push(` console.log(res.raw_body);\n });\n`) diff --git a/packages/hoppscotch-app/helpers/codegen/generators/php-curl.js b/packages/hoppscotch-app/helpers/codegen/generators/php-curl.js index 0b71d976..3f6022d1 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/php-curl.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/php-curl.js @@ -47,31 +47,33 @@ export const PhpCurlCodegen = { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { let requestBody = rawInput ? rawParams : rawRequestBody - if ( - !isJSONContentType(contentType) && - rawInput && - !contentType.includes("x-www-form-urlencoded") - ) { - const toRemove = /[\n {}]/gim - const toReplace = /:/gim - const parts = requestBody.replace(toRemove, "").replace(toReplace, "=>") - requestBody = `array(${parts})` - } else if (isJSONContentType(contentType)) { - requestBody = JSON.stringify(requestBody) - } else if (contentType.includes("x-www-form-urlencoded")) { - if (requestBody.includes("=")) { - requestBody = `"${requestBody}"` - } else { - const requestObject = JSON.parse(requestBody) - requestBody = `"${Object.keys(requestObject) - .map((key) => `${key}=${requestObject[key]}`) - .join("&")}"` + if (contentType && requestBody) { + if ( + !isJSONContentType(contentType) && + rawInput && + !contentType.includes("x-www-form-urlencoded") + ) { + const toRemove = /[\n {}]/gim + const toReplace = /:/gim + const parts = requestBody + .replace(toRemove, "") + .replace(toReplace, "=>") + requestBody = `array(${parts})` + } else if (isJSONContentType(contentType)) { + requestBody = JSON.stringify(requestBody) + } else if (contentType.includes("x-www-form-urlencoded")) { + if (requestBody.includes("=")) { + requestBody = `"${requestBody}"` + } else { + const requestObject = JSON.parse(requestBody) + requestBody = `"${Object.keys(requestObject) + .map((key) => `${key}=${requestObject[key]}`) + .join("&")}"` + } } + + requestString.push(` CURLOPT_POSTFIELDS => ${requestBody},\n`) } - if (contentType) { - genHeaders.push(` "Content-Type: ${contentType}; charset=utf-8",\n`) - } - requestString.push(` CURLOPT_POSTFIELDS => ${requestBody},\n`) } if (headers.length > 0) { diff --git a/packages/hoppscotch-app/helpers/codegen/generators/powershell-restmethod.js b/packages/hoppscotch-app/helpers/codegen/generators/powershell-restmethod.js index 40880627..13d2fcd7 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/powershell-restmethod.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/powershell-restmethod.js @@ -14,7 +14,6 @@ export const PowershellRestmethodCodegen = { rawInput, rawParams, rawRequestBody, - contentType, headers, }) => { const methodsWithBody = ["Put", "Post", "Delete"] @@ -30,8 +29,10 @@ export const PowershellRestmethodCodegen = { ) const requestBody = rawInput ? rawParams : rawRequestBody - if (requestBody.length !== 0 && includeBody) { - variables = variables.concat(`$body = @'\n${requestBody}\n'@\n\n`) + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if (requestBody && includeBody) { + variables = variables.concat(`$body = @'\n${requestBody}\n'@\n\n`) + } } if (headers) { headers.forEach(({ key, value }) => { @@ -39,11 +40,6 @@ export const PowershellRestmethodCodegen = { }) } - if (contentType) { - genHeaders.push(` 'Content-Type' = '${contentType}; charset=utf-8'\n`) - requestString.push(` -ContentType '${contentType}; charset=utf-8'`) - } - if (auth === "Basic Auth") { const basic = `${httpUser}:${httpPassword}` genHeaders.push( @@ -55,11 +51,13 @@ export const PowershellRestmethodCodegen = { genHeaders.push(` 'Authorization' = 'Bearer ${bearerToken}'\n`) } genHeaders = genHeaders.join("").slice(0, -1) - variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`) - requestString.push(` -Headers $headers`) - if (includeBody) { + if (genHeaders) { + variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`) + requestString.push(` -Headers $headers`) + } + if (requestBody && includeBody) { requestString.push(` -Body $body`) } - return `${variables}\n${requestString.join("")}` + return `${variables}${requestString.join("")}` }, } diff --git a/packages/hoppscotch-app/helpers/codegen/generators/python-http-client.js b/packages/hoppscotch-app/helpers/codegen/generators/python-http-client.js index e061ac46..1d3a63c4 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/python-http-client.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/python-http-client.js @@ -69,25 +69,28 @@ export const PythonHttpClientCodegen = { requestString.push(`payload = ''\n`) } if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { - genHeaders.push(`'Content-Type': '${contentType}'`) requestString.push(...printHeaders(genHeaders)) - if (isJSONContentType(contentType)) { - requestBody = JSON.stringify(requestBody) - requestString.push(`payload = ${requestBody}\n`) - } else if (contentType.includes("x-www-form-urlencoded")) { - const formData = [] - if (requestBody.includes("=")) { - requestBody.split("&").forEach((rq) => { - const [key, val] = rq.split("=") - formData.push(`('${key}', '${val}')`) - }) - } - if (formData.length) { - requestString.push(`payload = [${formData.join(",\n ")}]\n`) + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestBody = JSON.stringify(requestBody) + requestString.push(`payload = ${requestBody}\n`) + } else if (contentType.includes("x-www-form-urlencoded")) { + const formData = [] + if (requestBody.includes("=")) { + requestBody.split("&").forEach((rq) => { + const [key, val] = rq.split("=") + formData.push(`('${key}', '${val}')`) + }) + } + if (formData.length) { + requestString.push(`payload = [${formData.join(",\n ")}]\n`) + } + } else { + requestString.push(`paylod = '''${requestBody}'''\n`) } } else { - requestString.push(`paylod = '''${requestBody}'''\n`) + requestString.push(`payload = ''\n`) } } requestString.push( diff --git a/packages/hoppscotch-app/helpers/codegen/generators/python-requests.js b/packages/hoppscotch-app/helpers/codegen/generators/python-requests.js index c0206277..5955e0d3 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/python-requests.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/python-requests.js @@ -54,36 +54,39 @@ export const PythonRequestsCodegen = { // initial request setup let requestBody = rawInput ? rawParams : rawRequestBody - if (method === "GET") { - requestString.push(...printHeaders(genHeaders)) - requestString.push(`response = requests.request(\n`) - requestString.push(` '${method}',\n`) - requestString.push(` '${url}${pathName}?${queryString}',\n`) - } - if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { - genHeaders.push(`'Content-Type': '${contentType}'`) - requestString.push(...printHeaders(genHeaders)) + let requestDataObj = "" + requestString.push(...printHeaders(genHeaders)) - if (isJSONContentType(contentType)) { - requestBody = JSON.stringify(requestBody) - requestString.push(`data = ${requestBody}\n`) - } else if (contentType.includes("x-www-form-urlencoded")) { - const formData = [] - if (requestBody.includes("=")) { - requestBody.split("&").forEach((rq) => { - const [key, val] = rq.split("=") - formData.push(`('${key}', '${val}')`) - }) + if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if (contentType && requestBody) { + if (isJSONContentType(contentType)) { + requestBody = JSON.stringify(requestBody) + requestDataObj = `data = ${requestBody}\n` + } else if (contentType.includes("x-www-form-urlencoded")) { + const formData = [] + if (requestBody.includes("=")) { + requestBody.split("&").forEach((rq) => { + const [key, val] = rq.split("=") + formData.push(`('${key}', '${val}')`) + }) + } + if (formData.length) { + requestDataObj = `data = [${formData.join(",\n ")}]\n` + } + } else { + requestDataObj = `data = '''${requestBody}'''\n` } - if (formData.length) { - requestString.push(`data = [${formData.join(",\n ")}]\n`) - } - } else { - requestString.push(`data = '''${requestBody}'''\n`) } - requestString.push(`response = requests.request(\n`) - requestString.push(` '${method}',\n`) - requestString.push(` '${url}${pathName}?${queryString}',\n`) + } + if (requestDataObj) { + requestString.push(requestDataObj) + } + + requestString.push(`response = requests.request(\n`) + requestString.push(` '${method}',\n`) + requestString.push(` '${url}${pathName}?${queryString}',\n`) + + if (requestDataObj && requestBody) { requestString.push(` data=data,\n`) } diff --git a/packages/hoppscotch-app/helpers/codegen/generators/ruby-net-http.js b/packages/hoppscotch-app/helpers/codegen/generators/ruby-net-http.js index 4487891f..a76efedb 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/ruby-net-http.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/ruby-net-http.js @@ -14,7 +14,6 @@ export const RubyNetHttpCodeGen = { rawInput, rawParams, rawRequestBody, - contentType, headers, }) => { const requestString = [] @@ -23,7 +22,9 @@ export const RubyNetHttpCodeGen = { // initial request setup let requestBody = rawInput ? rawParams : rawRequestBody - requestBody = requestBody.replace(/'/g, "\\'") // escape single-quotes for single-quoted string compatibility + if (requestBody) { + requestBody = requestBody.replaceAll(/'/g, "\\'") // escape single-quotes for single-quoted string compatibility + } const verbs = [ { verb: "GET", rbMethod: "Get" }, @@ -35,14 +36,10 @@ export const RubyNetHttpCodeGen = { // create URI and request const verb = verbs.find((v) => v.verb === method) + if (!verb) return "" requestString.push(`uri = URI.parse('${url}${pathName}?${queryString}')\n`) requestString.push(`request = Net::HTTP::${verb.rbMethod}.new(uri)`) - // content type - if (contentType) { - requestString.push(`request['Content-Type'] = '${contentType}'`) - } - // custom headers if (headers) { headers.forEach(({ key, value }) => { @@ -60,7 +57,7 @@ export const RubyNetHttpCodeGen = { } // set body - if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) { requestString.push(`request.body = '${requestBody}'\n`) } diff --git a/packages/hoppscotch-app/helpers/codegen/generators/salesforce-apex.js b/packages/hoppscotch-app/helpers/codegen/generators/salesforce-apex.js index 250f7031..72180faa 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/salesforce-apex.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/salesforce-apex.js @@ -14,17 +14,18 @@ export const SalesforceApexCodegen = { rawInput, rawParams, rawRequestBody, - contentType, headers, }) => { const requestString = [] // initial request setup let requestBody = rawInput ? rawParams : rawRequestBody - requestBody = JSON.stringify(requestBody) - .replace(/^"|"$/g, "") - .replace(/\\"/g, '"') - .replace(/'/g, "\\'") // Apex uses single quotes for strings + if (requestBody) { + requestBody = JSON.stringify(requestBody) + .replace(/^"|"$/g, "") + .replace(/\\"/g, '"') + .replace(/'/g, "\\'") // Apex uses single quotes for strings + } // create request requestString.push(`HttpRequest request = new HttpRequest();\n`) @@ -47,13 +48,6 @@ export const SalesforceApexCodegen = { ) } - // content type - if (contentType) { - requestString.push( - `request.setHeader('Content-Type', '${contentType}');\n` - ) - } - // custom headers if (headers) { headers.forEach(({ key, value }) => { @@ -66,7 +60,7 @@ export const SalesforceApexCodegen = { requestString.push(`\n`) // set body - if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { + if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) { requestString.push(`request.setBody('${requestBody}');\n\n`) } diff --git a/packages/hoppscotch-app/helpers/codegen/generators/shell-httpie.js b/packages/hoppscotch-app/helpers/codegen/generators/shell-httpie.js index 0623847b..0b1f2a06 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/shell-httpie.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/shell-httpie.js @@ -14,7 +14,6 @@ export const ShellHttpieCodegen = { rawInput, rawParams, rawRequestBody, - contentType, headers, }) => { const methodsWithBody = ["POST", "PUT", "PATCH", "DELETE"] @@ -22,8 +21,9 @@ export const ShellHttpieCodegen = { const requestString = [] let requestBody = rawInput ? rawParams : rawRequestBody - requestBody = requestBody.replace(/'/g, "\\'") - if (requestBody.length !== 0 && includeBody) { + if (requestBody && includeBody) { + requestBody = requestBody.replace(/'/g, "\\'") + // Send request body via redirected input requestString.push(`echo -n $'${requestBody}' | `) } @@ -41,11 +41,6 @@ export const ShellHttpieCodegen = { escapedUrl = escapedUrl.replace(/'/g, "\\'") requestString.push(` ${method} $'${escapedUrl}'`) - // All headers - if (contentType) { - requestString.push(` 'Content-Type:${contentType}; charset=utf-8'`) - } - if (headers) { headers.forEach(({ key, value }) => { requestString.push( diff --git a/packages/hoppscotch-app/helpers/codegen/generators/shell-wget.js b/packages/hoppscotch-app/helpers/codegen/generators/shell-wget.js index 537d6fd9..133065c5 100644 --- a/packages/hoppscotch-app/helpers/codegen/generators/shell-wget.js +++ b/packages/hoppscotch-app/helpers/codegen/generators/shell-wget.js @@ -14,10 +14,10 @@ export const ShellWgetCodegen = { rawInput, rawParams, rawRequestBody, - contentType, headers, }) => { const requestString = [] + const requestBody = rawInput ? rawParams : rawRequestBody requestString.push(`wget -O - --method=${method}`) requestString.push(` '${url}${pathName}?${queryString}'`) if (auth === "Basic Auth") { @@ -35,11 +35,7 @@ export const ShellWgetCodegen = { if (key) requestString.push(` --header='${key}: ${value}'`) }) } - if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { - const requestBody = rawInput ? rawParams : rawRequestBody - requestString.push( - ` --header='Content-Type: ${contentType}; charset=utf-8'` - ) + if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) { requestString.push(` --body-data='${requestBody}'`) } return requestString.join(" \\\n")