fix: code generators (#1985)

Co-authored-by: liyasthomas <liyascthomas@gmail.com>
This commit is contained in:
Deepanshu Dhruw
2021-11-30 07:46:45 +05:30
committed by GitHub
parent 2a59557851
commit 520ac8ede5
21 changed files with 285 additions and 263 deletions

View File

@@ -28,6 +28,7 @@ export const CLibcurlCodegen = {
) )
requestString.push(`struct curl_slist *headers = NULL;`) requestString.push(`struct curl_slist *headers = NULL;`)
// append header attributes
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { headers.forEach(({ key, value }) => {
if (key) 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)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if (contentType.includes("x-www-form-urlencoded")) { if (contentType && contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"` requestBody = `"${requestBody}"`
} else requestBody = JSON.stringify(requestBody) } else {
requestBody = requestBody ? JSON.stringify(requestBody) : null
}
requestString.push( // set request-body
`headers = curl_slist_append(headers, "Content-Type: ${contentType}");` if (requestBody) {
) requestString.push(
requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);") `curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${requestBody});`
requestString.push( )
`curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, ${requestBody});` }
) }
} else
requestString.push("curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);")
requestString.push(`CURLcode ret = curl_easy_perform(hnd);`) requestString.push(`CURLcode ret = curl_easy_perform(hnd);`)
return requestString.join("\n") return requestString.join("\n")

View File

@@ -23,7 +23,9 @@ export const CsRestsharpCodegen = {
// initial request setup // initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody 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 // prepare data
let requestDataFormat let requestDataFormat
@@ -62,13 +64,6 @@ export const CsRestsharpCodegen = {
) )
} }
// content type
if (contentType) {
requestString.push(
`request.AddHeader("Content-Type", "${contentType}");\n`
)
}
// custom headers // custom headers
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { headers.forEach(({ key, value }) => {
@@ -81,7 +76,7 @@ export const CsRestsharpCodegen = {
requestString.push(`\n`) requestString.push(`\n`)
// set body // set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push( requestString.push(
`request.AddParameter("${requestContentType}", @"${requestBody}", ParameterType.RequestBody);\n\n` `request.AddParameter("${requestContentType}", @"${requestBody}", ParameterType.RequestBody);\n\n`
) )
@@ -89,7 +84,11 @@ export const CsRestsharpCodegen = {
// process // process
const verb = verbs.find((v) => v.verb === method) 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 // analyse result
requestString.push( requestString.push(

View File

@@ -14,7 +14,6 @@ export const CurlCodegen = {
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody, rawRequestBody,
contentType,
headers, headers,
}) => { }) => {
const requestString = [] const requestString = []
@@ -36,8 +35,9 @@ export const CurlCodegen = {
}) })
} }
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
const requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(` -H 'Content-Type: ${contentType}; charset=utf-8'`) requestBody = requestBody || ""
requestString.push(` -d '${requestBody}'`) requestString.push(` -d '${requestBody}'`)
} }
return requestString.join(" \\\n") return requestString.join(" \\\n")

View File

@@ -23,23 +23,28 @@ export const GoNativeCodegen = {
let genHeaders = [] let genHeaders = []
// initial request setup // initial request setup
const requestBody = rawInput ? rawParams : rawRequestBody 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)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
genHeaders.push(`req.Header.Set("Content-Type", "${contentType}")\n`) if (contentType && requestBody) {
if (isJSONContentType(contentType)) { if (isJSONContentType(contentType)) {
requestString.push(`var reqBody = []byte(\`${requestBody}\`)\n\n`) 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( requestString.push(
`req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", bytes.NewBuffer(reqBody))\n` `req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", nil)\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}", nil)\n`
)
} }
// headers // headers

View File

@@ -26,16 +26,26 @@ export const JavaOkhttpCodegen = {
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if (contentType.includes("x-www-form-urlencoded")) { if (contentType && contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"` requestBody = `"${requestBody}"`
} else requestBody = JSON.stringify(requestBody) } else {
requestBody = requestBody ? JSON.stringify(requestBody) : null
}
requestString.push( if (contentType) {
`MediaType mediaType = MediaType.parse("${contentType}");` requestString.push(
) `MediaType mediaType = MediaType.parse("${contentType}");`
requestString.push( )
`RequestBody body = RequestBody.create(mediaType,${requestBody});` }
) 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()") requestString.push("Request request = new Request.Builder()")

View File

@@ -31,8 +31,9 @@ export const JavaUnirestCodegen = {
] ]
// create client and request // create client and request
const verb = verbs.find((v) => v.verb === method) const verb = verbs.find((v) => v.verb === method)
const unirestMethod = verb.unirestMethod || "get"
requestString.push( 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") { if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}` const basic = `${httpUser}:${httpPassword}`
@@ -52,21 +53,21 @@ export const JavaUnirestCodegen = {
} }
}) })
} }
if (contentType) {
requestString.push(`.header("Content-Type", "${contentType}")\n`)
}
// set body // set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
if (contentType.includes("x-www-form-urlencoded")) { if (contentType && requestBody) {
requestBody = `"${requestBody}"` if (contentType.includes("x-www-form-urlencoded")) {
} else { requestBody = `"${requestBody}"`
requestBody = JSON.stringify(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("") return requestString.join("")
}, },
} }

View File

@@ -35,14 +35,18 @@ export const JavascriptFetchCodegen = {
} }
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if (isJSONContentType(contentType)) {
requestBody = `JSON.stringify(${requestBody})` if (contentType && requestBody) {
} else if (contentType.includes("x-www-form-urlencoded")) { if (isJSONContentType(contentType)) {
requestBody = `"${requestBody}"` requestBody = `JSON.stringify(${requestBody})`
} else if (contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
}
} }
requestString.push(` body: ${requestBody},\n`) if (requestBody) {
genHeaders.push(` "Content-Type": "${contentType}; charset=utf-8",\n`) requestString.push(` body: ${requestBody},\n`)
}
} }
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { headers.forEach(({ key, value }) => {
@@ -50,13 +54,11 @@ export const JavascriptFetchCodegen = {
}) })
} }
genHeaders = genHeaders.join("").slice(0, -2) 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(' credentials: "same-origin"\n')
requestString.push("}).then(function(response) {\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(" return response.text()\n")
requestString.push("}).catch(function(e) {\n") requestString.push("}).catch(function(e) {\n")
requestString.push(" console.error(e)\n") requestString.push(" console.error(e)\n")

View File

@@ -13,8 +13,8 @@ export const JavascriptJqueryCodegen = {
method, method,
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody,
contentType, contentType,
rawRequestBody,
headers, headers,
}) => { }) => {
const requestString = [] const requestString = []
@@ -24,10 +24,15 @@ export const JavascriptJqueryCodegen = {
`jQuery.ajax({\n url: "${url}${pathName}?${queryString}"` `jQuery.ajax({\n url: "${url}${pathName}?${queryString}"`
) )
requestString.push(`,\n method: "${method.toUpperCase()}"`) requestString.push(`,\n method: "${method.toUpperCase()}"`)
const requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if (requestBody.length !== 0) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
requestString.push(`,\n body: ${requestBody}`) if (contentType && contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
} else {
requestBody = requestBody.replaceAll("}", " }")
}
requestString.push(`,\n data: ${requestBody}`)
} }
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { 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") { if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}` const basic = `${httpUser}:${httpPassword}`
genHeaders.push( genHeaders.push(
@@ -50,10 +50,12 @@ export const JavascriptJqueryCodegen = {
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") { } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`) genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
} }
requestString.push( if (genHeaders.length > 0) {
`,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n})` requestString.push(
) `,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }`
requestString.push(".then(response => {\n") )
}
requestString.push("\n}).then(response => {\n")
requestString.push(" console.log(response);\n") requestString.push(" console.log(response);\n")
requestString.push("})") requestString.push("})")
requestString.push(".catch(e => {\n") requestString.push(".catch(e => {\n")

View File

@@ -21,6 +21,9 @@ export const JavascriptXhrCodegen = {
}) => { }) => {
const requestString = [] const requestString = []
requestString.push("const xhr = new XMLHttpRequest()") 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 user = auth === "Basic Auth" ? `'${httpUser}'` : null
const password = auth === "Basic Auth" ? `'${httpPassword}'` : null const password = auth === "Basic Auth" ? `'${httpPassword}'` : null
@@ -40,14 +43,14 @@ export const JavascriptXhrCodegen = {
} }
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if (isJSONContentType(contentType)) { if (contentType && requestBody) {
requestBody = `JSON.stringify(${requestBody})` if (isJSONContentType(contentType)) {
} else if (contentType.includes("x-www-form-urlencoded")) { requestBody = `JSON.stringify(${requestBody})`
requestBody = `"${requestBody}"` } else if (contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
}
} }
requestString.push( requestBody = requestBody || ""
`xhr.setRequestHeader('Content-Type', '${contentType}; charset=utf-8')`
)
requestString.push(`xhr.send(${requestBody})`) requestString.push(`xhr.send(${requestBody})`)
} else { } else {
requestString.push("xhr.send()") requestString.push("xhr.send()")

View File

@@ -19,22 +19,31 @@ export const NodejsAxiosCodegen = {
}) => { }) => {
const requestString = [] const requestString = []
const genHeaders = [] 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( requestString.push(
`axios.${method.toLowerCase()}('${url}${pathName}?${queryString}'` `axios.${method.toLowerCase()}('${url}${pathName}?${queryString}'`
) )
if (requestBody.length !== 0) { if (requestBody && requestBody.length !== 0) {
requestString.push(", ") requestString.push(", ")
} }
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { 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") { if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}` const basic = `${httpUser}:${httpPassword}`
genHeaders.push( genHeaders.push(
@@ -45,10 +54,15 @@ export const NodejsAxiosCodegen = {
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") { } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`) genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
} }
requestString.push( if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
`${requestBody},{ \n headers : {${genHeaders.join("").slice(0, -2)}}\n})` requestString.push(`${requestBody},`)
) }
requestString.push(".then(response => {\n") 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(" console.log(response);\n")
requestString.push("})") requestString.push("})")
requestString.push(".catch(e => {\n") requestString.push(".catch(e => {\n")

View File

@@ -43,16 +43,11 @@ export const NodejsNativeCodegen = {
let requestBody let requestBody
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
requestBody = rawInput ? rawParams : rawRequestBody requestBody = rawInput ? rawParams : rawRequestBody
if (isJSONContentType(contentType)) { if (isJSONContentType(contentType) && requestBody) {
requestBody = `JSON.stringify(${requestBody})` requestBody = `JSON.stringify(${requestBody})`
} else { } else if (requestBody) {
requestBody = `\`${requestBody}\`` requestBody = `\`${requestBody}\``
} }
if (contentType) {
genHeaders.push(
` "Content-Type": "${contentType}; charset=utf-8",\n`
)
}
} }
if (headers) { if (headers) {
@@ -62,7 +57,7 @@ export const NodejsNativeCodegen = {
} }
if (genHeaders.length > 0 || headers.length > 0) { if (genHeaders.length > 0 || headers.length > 0) {
requestString.push( requestString.push(
` headers: {\n${genHeaders.join("").slice(0, -2)}\n }` ` headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n`
) )
} }
requestString.push(`};\n\n`) requestString.push(`};\n\n`)

View File

@@ -40,31 +40,30 @@ export const NodejsRequestCodegen = {
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
let reqBodyType = "formData" let reqBodyType = "formData"
if (isJSONContentType(contentType)) { if (contentType && requestBody) {
requestBody = `JSON.stringify(${requestBody})` if (isJSONContentType(contentType)) {
reqBodyType = "body" requestBody = `JSON.stringify(${requestBody})`
} else if (contentType.includes("x-www-form-urlencoded")) { reqBodyType = "body"
const formData = [] } else if (contentType.includes("x-www-form-urlencoded")) {
if (requestBody.includes("=")) { const formData = []
requestBody.split("&").forEach((rq) => { if (requestBody.includes("=")) {
const [key, val] = rq.split("=") requestBody.split("&").forEach((rq) => {
formData.push(`"${key}": "${val}"`) 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) { if (requestBody) {
genHeaders.push( requestString.push(`,\n ${reqBodyType}: ${requestBody}`)
` "Content-Type": "${contentType}; charset=utf-8",\n`
)
} }
requestString.push(`,\n ${reqBodyType}: ${requestBody}`)
} }
if (headers.length > 0) { if (headers.length > 0) {

View File

@@ -42,31 +42,30 @@ export const NodejsUnirestCodegen = {
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
let reqBodyType = "formData" let reqBodyType = "formData"
if (isJSONContentType(contentType)) { if (contentType && requestBody) {
requestBody = `\`${requestBody}\`` if (isJSONContentType(contentType)) {
reqBodyType = "send" requestBody = `\`${requestBody}\``
} else if (contentType.includes("x-www-form-urlencoded")) { reqBodyType = "send"
const formData = [] } else if (contentType.includes("x-www-form-urlencoded")) {
if (requestBody.includes("=")) { const formData = []
requestBody.split("&").forEach((rq) => { if (requestBody.includes("=")) {
const [key, val] = rq.split("=") requestBody.split("&").forEach((rq) => {
formData.push(`"${key}": "${val}"`) 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) { if (requestBody) {
genHeaders.push( requestString.push(`\n.${reqBodyType}( ${requestBody})`)
` "Content-Type": "${contentType}; charset=utf-8",\n`
)
} }
requestString.push(`.\n ${reqBodyType}( ${requestBody})`)
} }
if (headers.length > 0) { if (headers.length > 0) {
@@ -76,11 +75,10 @@ export const NodejsUnirestCodegen = {
} }
if (genHeaders.length > 0 || headers.length > 0) { if (genHeaders.length > 0 || headers.length > 0) {
requestString.push( 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(`\n.end(function (res) {\n`)
requestString.push(` if (res.error) throw new Error(res.error);\n`) requestString.push(` if (res.error) throw new Error(res.error);\n`)
requestString.push(` console.log(res.raw_body);\n });\n`) requestString.push(` console.log(res.raw_body);\n });\n`)

View File

@@ -47,31 +47,33 @@ export const PhpCurlCodegen = {
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if ( if (contentType && requestBody) {
!isJSONContentType(contentType) && if (
rawInput && !isJSONContentType(contentType) &&
!contentType.includes("x-www-form-urlencoded") rawInput &&
) { !contentType.includes("x-www-form-urlencoded")
const toRemove = /[\n {}]/gim ) {
const toReplace = /:/gim const toRemove = /[\n {}]/gim
const parts = requestBody.replace(toRemove, "").replace(toReplace, "=>") const toReplace = /:/gim
requestBody = `array(${parts})` const parts = requestBody
} else if (isJSONContentType(contentType)) { .replace(toRemove, "")
requestBody = JSON.stringify(requestBody) .replace(toReplace, "=>")
} else if (contentType.includes("x-www-form-urlencoded")) { requestBody = `array(${parts})`
if (requestBody.includes("=")) { } else if (isJSONContentType(contentType)) {
requestBody = `"${requestBody}"` requestBody = JSON.stringify(requestBody)
} else { } else if (contentType.includes("x-www-form-urlencoded")) {
const requestObject = JSON.parse(requestBody) if (requestBody.includes("=")) {
requestBody = `"${Object.keys(requestObject) requestBody = `"${requestBody}"`
.map((key) => `${key}=${requestObject[key]}`) } else {
.join("&")}"` 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) { if (headers.length > 0) {

View File

@@ -14,7 +14,6 @@ export const PowershellRestmethodCodegen = {
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody, rawRequestBody,
contentType,
headers, headers,
}) => { }) => {
const methodsWithBody = ["Put", "Post", "Delete"] const methodsWithBody = ["Put", "Post", "Delete"]
@@ -30,8 +29,10 @@ export const PowershellRestmethodCodegen = {
) )
const requestBody = rawInput ? rawParams : rawRequestBody const requestBody = rawInput ? rawParams : rawRequestBody
if (requestBody.length !== 0 && includeBody) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
variables = variables.concat(`$body = @'\n${requestBody}\n'@\n\n`) if (requestBody && includeBody) {
variables = variables.concat(`$body = @'\n${requestBody}\n'@\n\n`)
}
} }
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { 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") { if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}` const basic = `${httpUser}:${httpPassword}`
genHeaders.push( genHeaders.push(
@@ -55,11 +51,13 @@ export const PowershellRestmethodCodegen = {
genHeaders.push(` 'Authorization' = 'Bearer ${bearerToken}'\n`) genHeaders.push(` 'Authorization' = 'Bearer ${bearerToken}'\n`)
} }
genHeaders = genHeaders.join("").slice(0, -1) genHeaders = genHeaders.join("").slice(0, -1)
variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`) if (genHeaders) {
requestString.push(` -Headers $headers`) variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`)
if (includeBody) { requestString.push(` -Headers $headers`)
}
if (requestBody && includeBody) {
requestString.push(` -Body $body`) requestString.push(` -Body $body`)
} }
return `${variables}\n${requestString.join("")}` return `${variables}${requestString.join("")}`
}, },
} }

View File

@@ -69,25 +69,28 @@ export const PythonHttpClientCodegen = {
requestString.push(`payload = ''\n`) requestString.push(`payload = ''\n`)
} }
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
genHeaders.push(`'Content-Type': '${contentType}'`)
requestString.push(...printHeaders(genHeaders)) requestString.push(...printHeaders(genHeaders))
if (isJSONContentType(contentType)) { if (contentType && requestBody) {
requestBody = JSON.stringify(requestBody) if (isJSONContentType(contentType)) {
requestString.push(`payload = ${requestBody}\n`) requestBody = JSON.stringify(requestBody)
} else if (contentType.includes("x-www-form-urlencoded")) { requestString.push(`payload = ${requestBody}\n`)
const formData = [] } else if (contentType.includes("x-www-form-urlencoded")) {
if (requestBody.includes("=")) { const formData = []
requestBody.split("&").forEach((rq) => { if (requestBody.includes("=")) {
const [key, val] = rq.split("=") requestBody.split("&").forEach((rq) => {
formData.push(`('${key}', '${val}')`) const [key, val] = rq.split("=")
}) formData.push(`('${key}', '${val}')`)
} })
if (formData.length) { }
requestString.push(`payload = [${formData.join(",\n ")}]\n`) if (formData.length) {
requestString.push(`payload = [${formData.join(",\n ")}]\n`)
}
} else {
requestString.push(`paylod = '''${requestBody}'''\n`)
} }
} else { } else {
requestString.push(`paylod = '''${requestBody}'''\n`) requestString.push(`payload = ''\n`)
} }
} }
requestString.push( requestString.push(

View File

@@ -54,36 +54,39 @@ export const PythonRequestsCodegen = {
// initial request setup // initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
if (method === "GET") { let requestDataObj = ""
requestString.push(...printHeaders(genHeaders)) 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))
if (isJSONContentType(contentType)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
requestBody = JSON.stringify(requestBody) if (contentType && requestBody) {
requestString.push(`data = ${requestBody}\n`) if (isJSONContentType(contentType)) {
} else if (contentType.includes("x-www-form-urlencoded")) { requestBody = JSON.stringify(requestBody)
const formData = [] requestDataObj = `data = ${requestBody}\n`
if (requestBody.includes("=")) { } else if (contentType.includes("x-www-form-urlencoded")) {
requestBody.split("&").forEach((rq) => { const formData = []
const [key, val] = rq.split("=") if (requestBody.includes("=")) {
formData.push(`('${key}', '${val}')`) 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`) if (requestDataObj) {
requestString.push(` '${url}${pathName}?${queryString}',\n`) 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`) requestString.push(` data=data,\n`)
} }

View File

@@ -14,7 +14,6 @@ export const RubyNetHttpCodeGen = {
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody, rawRequestBody,
contentType,
headers, headers,
}) => { }) => {
const requestString = [] const requestString = []
@@ -23,7 +22,9 @@ export const RubyNetHttpCodeGen = {
// initial request setup // initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody 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 = [ const verbs = [
{ verb: "GET", rbMethod: "Get" }, { verb: "GET", rbMethod: "Get" },
@@ -35,14 +36,10 @@ export const RubyNetHttpCodeGen = {
// create URI and request // create URI and request
const verb = verbs.find((v) => v.verb === method) const verb = verbs.find((v) => v.verb === method)
if (!verb) return ""
requestString.push(`uri = URI.parse('${url}${pathName}?${queryString}')\n`) requestString.push(`uri = URI.parse('${url}${pathName}?${queryString}')\n`)
requestString.push(`request = Net::HTTP::${verb.rbMethod}.new(uri)`) requestString.push(`request = Net::HTTP::${verb.rbMethod}.new(uri)`)
// content type
if (contentType) {
requestString.push(`request['Content-Type'] = '${contentType}'`)
}
// custom headers // custom headers
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { headers.forEach(({ key, value }) => {
@@ -60,7 +57,7 @@ export const RubyNetHttpCodeGen = {
} }
// set body // set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push(`request.body = '${requestBody}'\n`) requestString.push(`request.body = '${requestBody}'\n`)
} }

View File

@@ -14,17 +14,18 @@ export const SalesforceApexCodegen = {
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody, rawRequestBody,
contentType,
headers, headers,
}) => { }) => {
const requestString = [] const requestString = []
// initial request setup // initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
requestBody = JSON.stringify(requestBody) if (requestBody) {
.replace(/^"|"$/g, "") requestBody = JSON.stringify(requestBody)
.replace(/\\"/g, '"') .replace(/^"|"$/g, "")
.replace(/'/g, "\\'") // Apex uses single quotes for strings .replace(/\\"/g, '"')
.replace(/'/g, "\\'") // Apex uses single quotes for strings
}
// create request // create request
requestString.push(`HttpRequest request = new HttpRequest();\n`) 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 // custom headers
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { headers.forEach(({ key, value }) => {
@@ -66,7 +60,7 @@ export const SalesforceApexCodegen = {
requestString.push(`\n`) requestString.push(`\n`)
// set body // set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push(`request.setBody('${requestBody}');\n\n`) requestString.push(`request.setBody('${requestBody}');\n\n`)
} }

View File

@@ -14,7 +14,6 @@ export const ShellHttpieCodegen = {
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody, rawRequestBody,
contentType,
headers, headers,
}) => { }) => {
const methodsWithBody = ["POST", "PUT", "PATCH", "DELETE"] const methodsWithBody = ["POST", "PUT", "PATCH", "DELETE"]
@@ -22,8 +21,9 @@ export const ShellHttpieCodegen = {
const requestString = [] const requestString = []
let requestBody = rawInput ? rawParams : rawRequestBody let requestBody = rawInput ? rawParams : rawRequestBody
requestBody = requestBody.replace(/'/g, "\\'") if (requestBody && includeBody) {
if (requestBody.length !== 0 && includeBody) { requestBody = requestBody.replace(/'/g, "\\'")
// Send request body via redirected input // Send request body via redirected input
requestString.push(`echo -n $'${requestBody}' | `) requestString.push(`echo -n $'${requestBody}' | `)
} }
@@ -41,11 +41,6 @@ export const ShellHttpieCodegen = {
escapedUrl = escapedUrl.replace(/'/g, "\\'") escapedUrl = escapedUrl.replace(/'/g, "\\'")
requestString.push(` ${method} $'${escapedUrl}'`) requestString.push(` ${method} $'${escapedUrl}'`)
// All headers
if (contentType) {
requestString.push(` 'Content-Type:${contentType}; charset=utf-8'`)
}
if (headers) { if (headers) {
headers.forEach(({ key, value }) => { headers.forEach(({ key, value }) => {
requestString.push( requestString.push(

View File

@@ -14,10 +14,10 @@ export const ShellWgetCodegen = {
rawInput, rawInput,
rawParams, rawParams,
rawRequestBody, rawRequestBody,
contentType,
headers, headers,
}) => { }) => {
const requestString = [] const requestString = []
const requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(`wget -O - --method=${method}`) requestString.push(`wget -O - --method=${method}`)
requestString.push(` '${url}${pathName}?${queryString}'`) requestString.push(` '${url}${pathName}?${queryString}'`)
if (auth === "Basic Auth") { if (auth === "Basic Auth") {
@@ -35,11 +35,7 @@ export const ShellWgetCodegen = {
if (key) requestString.push(` --header='${key}: ${value}'`) if (key) requestString.push(` --header='${key}: ${value}'`)
}) })
} }
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) { if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
const requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(
` --header='Content-Type: ${contentType}; charset=utf-8'`
)
requestString.push(` --body-data='${requestBody}'`) requestString.push(` --body-data='${requestBody}'`)
} }
return requestString.join(" \\\n") return requestString.join(" \\\n")