Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
fix: code generators (#1985)
Deepanshu Dhruw520ac8ede5b3
diff --git a/packages/hoppscotch-app/helpers/codegen/generators/c-libcurl.js b/packages/hoppscotch-app/helpers/codegen/generators/c-libcurl.jsindex 1d537760b..7cb2b5987 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 attributesif (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.jsindex c3452fac1..597deaa73 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 setuplet 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 datalet requestDataFormat@@ -62,13 +64,6 @@ export const CsRestsharpCodegen = {)}- // content type- if (contentType) {- requestString.push(- `request.AddHeader("Content-Type", "${contentType}");\n`- )- }-// custom headersif (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 = {// processconst 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 resultrequestString.push(diff --git a/packages/hoppscotch-app/helpers/codegen/generators/curl.js b/packages/hoppscotch-app/helpers/codegen/generators/curl.jsindex 2b7e18d1d..41cb79189 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.jsindex 3339b265c..8f5a6917e 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 setupconst 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`+ )}// headersdiff --git a/packages/hoppscotch-app/helpers/codegen/generators/java-okhttp.js b/packages/hoppscotch-app/helpers/codegen/generators/java-okhttp.jsindex 2225c4060..1bec7ef09 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.jsindex c257c76e9..bb696d6e6 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 requestconst verb = verbs.find((v) => v.verb === method)+ const unirestMethod = verb.unirestMethod || "get"requestString.push(- `HttpResponse<String> response = Unirest.${verb.unirestMethod}("${url}${pathName}?${queryString}")\n`+ `HttpResponse<String> 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 bodyif (["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.jsindex 7804e8d28..665cd6d13 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.jsindex b2ca1c0b3..6626fc2c7 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.jsindex 3c752d05a..63e1a8f12 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}'` : nullconst 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.jsindex 349e2d259..325d6d0fc 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.jsindex cc551ccac..e4d75f111 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 requestBodyif (["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.jsindex cbdf218a0..6e8ee9927 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 : rawRequestBodylet 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.jsindex dabab4982..f533b52af 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 : rawRequestBodylet 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.jsindex 0b71d9766..3f6022d10 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.jsindex 40880627c..13d2fcd70 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.jsindex e061ac462..1d3a63c44 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.jsindex c02062774..5955e0d33 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 setuplet 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 (formData.length) {- requestString.push(`data = [${formData.join(",\n ")}]\n`)+ 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`}- } 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.jsindex 4487891f8..a76efedb5 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 setuplet 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 requestconst 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 headersif (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.jsindex 250f70313..72180faa4 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 setuplet 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 requestrequestString.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 headersif (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.jsindex 0623847b5..0b1f2a06a 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 inputrequestString.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.jsindex 537d6fd97..133065c56 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 : rawRequestBodyrequestString.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")