fix: remove old codegen code

This commit is contained in:
Andrew Bastin
2021-12-30 13:34:00 +05:30
parent aa4fedb71c
commit 50e30ee4ea
23 changed files with 0 additions and 1922 deletions

View File

@@ -1,91 +0,0 @@
import { codegens } from "../codegen"
const TEST_URL = "https://httpbin.org"
const TEST_PATH_NAME = "/path/to"
const TEST_QUERY_STRING = "?a=b"
const TEST_HTTP_USER = "mockUser"
const TEST_HTTP_PASSWORD = "mockPassword"
const TEST_BEARER_TOKEN = "abcdefghijklmn"
const TEST_RAW_REQUEST_BODY = "foo=bar&baz=qux"
const TEST_RAW_PARAMS_JSON = '{"foo": "bar", "baz": "qux"}'
const TEST_RAW_PARAMS_XML = `<?xml version='1.0' encoding='utf-8'?>
<xml>
<element foo="bar"></element>
</xml>`
const TEST_HEADERS = [
{ key: "h1", value: "h1v" },
{ key: "h2", value: "h2v" },
]
codegens.forEach((codegen) => {
describe(`generate request for ${codegen.name}`, () => {
const testCases = [
[
"generate GET request",
{
url: TEST_URL,
pathName: TEST_PATH_NAME,
queryString: TEST_QUERY_STRING,
auth: "Basic Auth",
httpUser: TEST_HTTP_USER,
httpPassword: TEST_HTTP_PASSWORD,
method: "GET",
rawInput: false,
rawParams: "",
rawRequestBody: "",
headers: TEST_HEADERS,
},
],
[
"generate POST request for JSON",
{
url: TEST_URL,
pathName: TEST_PATH_NAME,
queryString: TEST_QUERY_STRING,
auth: "Bearer Token",
bearerToken: TEST_BEARER_TOKEN,
method: "POST",
rawInput: true,
rawParams: TEST_RAW_PARAMS_JSON,
rawRequestBody: "",
contentType: "application/json",
headers: TEST_HEADERS,
},
],
[
"generate POST request for XML",
{
url: TEST_URL,
pathName: TEST_PATH_NAME,
queryString: TEST_QUERY_STRING,
auth: "OAuth 2.0",
bearerToken: TEST_BEARER_TOKEN,
method: "POST",
rawInput: true,
rawParams: TEST_RAW_PARAMS_XML,
rawRequestBody: "",
contentType: "application/xml",
headers: TEST_HEADERS,
},
],
[
"generate PUT request for www-form-urlencoded",
{
url: TEST_URL,
pathName: TEST_PATH_NAME,
queryString: TEST_QUERY_STRING,
method: "PUT",
rawInput: false,
rawRequestBody: TEST_RAW_REQUEST_BODY,
contentType: "application/x-www-form-urlencoded",
headers: [],
},
],
]
test.each(testCases)("%s", (_, context) => {
const result = codegen.generator(context)
expect(result).toMatchSnapshot()
})
})
})

View File

@@ -1,209 +0,0 @@
import {
FormDataKeyValue,
HoppRESTHeader,
HoppRESTParam,
} from "@hoppscotch/data"
import { EffectiveHoppRESTRequest } from "../utils/EffectiveURL"
import { CLibcurlCodegen } from "./generators/c-libcurl"
import { CsRestsharpCodegen } from "./generators/cs-restsharp"
import { CurlCodegen } from "./generators/curl"
import { GoNativeCodegen } from "./generators/go-native"
import { JavaOkhttpCodegen } from "./generators/java-okhttp"
import { JavaUnirestCodegen } from "./generators/java-unirest"
import { JavascriptFetchCodegen } from "./generators/javascript-fetch"
import { JavascriptJqueryCodegen } from "./generators/javascript-jquery"
import { JavascriptXhrCodegen } from "./generators/javascript-xhr"
import { NodejsAxiosCodegen } from "./generators/nodejs-axios"
import { NodejsNativeCodegen } from "./generators/nodejs-native"
import { NodejsRequestCodegen } from "./generators/nodejs-request"
import { NodejsUnirestCodegen } from "./generators/nodejs-unirest"
import { PhpCurlCodegen } from "./generators/php-curl"
import { PowershellRestmethodCodegen } from "./generators/powershell-restmethod"
import { PythonHttpClientCodegen } from "./generators/python-http-client"
import { PythonRequestsCodegen } from "./generators/python-requests"
import { RubyNetHttpCodeGen } from "./generators/ruby-net-http"
import { SalesforceApexCodegen } from "./generators/salesforce-apex"
import { ShellHttpieCodegen } from "./generators/shell-httpie"
import { ShellWgetCodegen } from "./generators/shell-wget"
/* Register code generators here.
* A code generator is defined as an object with the following structure.
*
* id: string
* name: string
* language: string // a string identifier used in ace editor for syntax highlighting
* // see node_modules/ace-builds/src-noconflict/mode-** files for valid value
* generator: (ctx) => string
*
*/
export const codegens = [
CLibcurlCodegen,
CsRestsharpCodegen,
CurlCodegen,
GoNativeCodegen,
JavaOkhttpCodegen,
JavaUnirestCodegen,
JavascriptFetchCodegen,
JavascriptJqueryCodegen,
JavascriptXhrCodegen,
NodejsAxiosCodegen,
NodejsNativeCodegen,
NodejsRequestCodegen,
NodejsUnirestCodegen,
PhpCurlCodegen,
PowershellRestmethodCodegen,
PythonHttpClientCodegen,
PythonRequestsCodegen,
RubyNetHttpCodeGen,
SalesforceApexCodegen,
ShellHttpieCodegen,
ShellWgetCodegen,
]
export type HoppCodegenContext = {
name: string
method: string
uri: string
url: string
pathName: string
auth: any // TODO: Change this
httpUser: string | null
httpPassword: string | null
bearerToken: string | null
headers: HoppRESTHeader[]
params: HoppRESTParam[]
bodyParams: FormDataKeyValue[]
rawParams: string | null
rawInput: boolean
rawRequestBody: string | null
contentType: string | null
queryString: string
}
export function generateCodeWithGenerator(
codegenID: string,
context: HoppCodegenContext
) {
if (codegenID) {
const gen = codegens.find(({ id }) => id === codegenID)
return gen ? gen.generator(context) : ""
}
return ""
}
function getCodegenAuth(
request: EffectiveHoppRESTRequest
): Pick<
HoppCodegenContext,
"auth" | "bearerToken" | "httpUser" | "httpPassword"
> {
if (!request.auth.authActive || request.auth.authType === "none") {
return {
auth: "None",
httpUser: null,
httpPassword: null,
bearerToken: null,
}
}
if (request.auth.authType === "basic") {
return {
auth: "Basic Auth",
httpUser: request.auth.username,
httpPassword: request.auth.password,
bearerToken: null,
}
} else {
return {
auth: "Bearer Token",
httpUser: null,
httpPassword: null,
bearerToken: request.auth.token,
}
}
}
function addhttps(url: string) {
if (!/^(?:f|ht)tps?:\/\//.test(url)) {
url = "https://" + url
}
return url
}
function getCodegenGeneralRESTInfo(
request: EffectiveHoppRESTRequest
): Pick<
HoppCodegenContext,
| "name"
| "uri"
| "url"
| "method"
| "queryString"
| "pathName"
| "params"
| "headers"
> {
let urlObj: URL
try {
urlObj = new URL(request.effectiveFinalURL)
} catch (error) {
urlObj = new URL(addhttps(request.effectiveFinalURL))
}
request.effectiveFinalParams.forEach(({ key, value }) => {
urlObj.searchParams.append(key, value)
})
// Remove authorization headers if auth is specified (because see #1798)
const finalHeaders =
request.auth.authActive && request.auth.authType !== "none"
? request.effectiveFinalHeaders
.filter((x) => x.key.toLowerCase() !== "authorization")
.map((x) => ({ ...x, active: true }))
: request.effectiveFinalHeaders.map((x) => ({ ...x, active: true }))
return {
name: request.name,
uri: request.effectiveFinalURL,
headers: finalHeaders,
params: request.effectiveFinalParams.map((x) => ({ ...x, active: true })),
method: request.method,
url: urlObj.origin,
queryString: `${urlObj.searchParams}`,
pathName: urlObj.pathname,
}
}
function getCodegenReqBodyData(
request: EffectiveHoppRESTRequest
): Pick<
HoppCodegenContext,
"rawRequestBody" | "rawInput" | "contentType" | "bodyParams" | "rawParams"
> {
return {
contentType: request.body.contentType,
rawInput: request.body.contentType !== "multipart/form-data",
rawRequestBody:
request.body.contentType !== "multipart/form-data"
? request.body.body
: null,
bodyParams:
request.body.contentType === "multipart/form-data"
? request.body.body
: [],
rawParams:
request.body.contentType !== "multipart/form-data"
? request.body.body
: null,
}
}
export function generateCodegenContext(
request: EffectiveHoppRESTRequest
): HoppCodegenContext {
return {
...getCodegenAuth(request),
...getCodegenGeneralRESTInfo(request),
...getCodegenReqBodyData(request),
}
}

View File

@@ -1,79 +0,0 @@
export const CLibcurlCodegen = {
id: "c-libcurl",
name: "C libcurl",
language: "c_cpp",
generator: ({
auth,
httpUser,
httpPassword,
method,
url,
pathName,
queryString,
bearerToken,
headers,
rawInput,
rawParams,
rawRequestBody,
contentType,
}) => {
const requestString = []
requestString.push("CURL *hnd = curl_easy_init();")
requestString.push(
`curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "${method}");`
)
requestString.push(
`curl_easy_setopt(hnd, CURLOPT_URL, "${url}${pathName}?${queryString}");`
)
requestString.push(`struct curl_slist *headers = NULL;`)
// append header attributes
if (headers) {
headers.forEach(({ key, value }) => {
if (key)
requestString.push(
`headers = curl_slist_append(headers, "${key}: ${value}");`
)
})
}
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
requestString.push(
`headers = curl_slist_append(headers, "Authorization: Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}");`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(
`headers = curl_slist_append(headers, "Authorization: Bearer ${bearerToken}");`
)
}
// 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 && contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
} else {
requestBody = requestBody ? JSON.stringify(requestBody) : null
}
// 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")
},
}

View File

@@ -1,102 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const CsRestsharpCodegen = {
id: "cs-restsharp",
name: "C# RestSharp",
language: "csharp",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
if (requestBody) {
requestBody = requestBody.replace(/"/g, '""') // escape quotes for C# verbatim string compatibility
}
// prepare data
let requestDataFormat
let requestContentType
if (isJSONContentType(contentType)) {
requestDataFormat = "DataFormat.Json"
requestContentType = "text/json"
} else {
requestDataFormat = "DataFormat.Xml"
requestContentType = "text/xml"
}
const verbs = [
{ verb: "GET", csMethod: "Get" },
{ verb: "POST", csMethod: "Post" },
{ verb: "PUT", csMethod: "Put" },
{ verb: "PATCH", csMethod: "Patch" },
{ verb: "DELETE", csMethod: "Delete" },
]
// create client and request
requestString.push(`var client = new RestClient("${url}");\n\n`)
requestString.push(
`var request = new RestRequest("${pathName}?${queryString}", ${requestDataFormat});\n\n`
)
// authentification
if (auth === "Basic Auth") {
requestString.push(
`client.Authenticator = new HttpBasicAuthenticator("${httpUser}", "${httpPassword}");\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(
`request.AddHeader("Authorization", "Bearer ${bearerToken}");\n`
)
}
// custom headers
if (headers) {
headers.forEach(({ key, value }) => {
if (key) {
requestString.push(`request.AddHeader("${key}", "${value}");\n`)
}
})
}
requestString.push(`\n`)
// set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push(
`request.AddParameter("${requestContentType}", @"${requestBody}", ParameterType.RequestBody);\n\n`
)
}
// process
const verb = verbs.find((v) => v.verb === method)
if (verb) {
requestString.push(`var response = client.${verb.csMethod}(request);\n\n`)
} else {
return ""
}
// analyse result
requestString.push(
`if (!response.IsSuccessful)\n{\n Console.WriteLine("An error occurred " + response.ErrorMessage);\n}\n\n`
)
requestString.push(`var result = response.Content;\n`)
return requestString.join("")
},
}

View File

@@ -1,45 +0,0 @@
export const CurlCodegen = {
id: "curl",
name: "cURL",
language: "sh",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
headers,
}) => {
const requestString = []
requestString.push(`curl -X ${method}`)
requestString.push(` '${url}${pathName}?${queryString}'`)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
requestString.push(
` -H 'Authorization: Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}'`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(` -H 'Authorization: Bearer ${bearerToken}'`)
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) requestString.push(` -H '${key}: ${value}'`)
})
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
requestBody = requestBody || ""
requestString.push(` -d '${requestBody}'`)
}
return requestString.join(" \\\n")
},
}

View File

@@ -1,87 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const GoNativeCodegen = {
id: "go-native",
name: "Go Native",
language: "golang",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
let genHeaders = []
// initial request setup
const requestBody = rawInput ? rawParams : rawRequestBody
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
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}", nil)\n`
)
}
} else {
requestString.push(
`req, err := http.NewRequest("${method}", "${url}${pathName}?${queryString}", nil)\n`
)
}
// headers
// auth
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
`req.Header.Set("Authorization", "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}")\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(
`req.Header.Set("Authorization", "Bearer ${bearerToken}")\n`
)
}
// custom headers
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(`req.Header.Set("${key}", "${value}")\n`)
})
}
genHeaders = genHeaders.join("").slice(0, -1)
requestString.push(`${genHeaders}\n`)
requestString.push(
`if err != nil {\n log.Fatalf("An error occurred %v", err)\n}\n\n`
)
// request boilerplate
requestString.push(`client := &http.Client{}\n`)
requestString.push(
`resp, err := client.Do(req)\nif err != nil {\n log.Fatalf("An error occurred %v", err)\n}\n\n`
)
requestString.push(`defer resp.Body.Close()\n`)
requestString.push(
`body, err := ioutil.ReadAll(resp.Body)\nif err != nil {\n log.Fatalln(err)\n}\n`
)
return requestString.join("")
},
}

View File

@@ -1,83 +0,0 @@
export const JavaOkhttpCodegen = {
id: "java-okhttp",
name: "Java OkHttp",
language: "java",
generator: ({
auth,
httpUser,
httpPassword,
method,
url,
pathName,
queryString,
bearerToken,
headers,
rawInput,
rawParams,
rawRequestBody,
contentType,
}) => {
const requestString = []
requestString.push(
"OkHttpClient client = new OkHttpClient().newBuilder().build();"
)
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
if (contentType && contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
} else {
requestBody = requestBody ? JSON.stringify(requestBody) : null
}
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()")
requestString.push(`.url("${url}${pathName}?${queryString}")`)
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
requestString.push(`.method("${method}", body)`)
} else {
requestString.push(`.method("${method}", null)`)
}
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
requestString.push(
`.addHeader("authorization", "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}") \n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(
`.addHeader("authorization", "Bearer ${bearerToken}" ) \n`
)
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) requestString.push(`.addHeader("${key}", "${value}")`)
})
}
requestString.push(`.build();`)
requestString.push("Response response = client.newCall(request).execute();")
return requestString.join("\n")
},
}

View File

@@ -1,73 +0,0 @@
export const JavaUnirestCodegen = {
id: "java-unirest",
name: "Java Unirest",
language: "java",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
const verbs = [
{ verb: "GET", unirestMethod: "get" },
{ verb: "POST", unirestMethod: "post" },
{ verb: "PUT", unirestMethod: "put" },
{ verb: "PATCH", unirestMethod: "patch" },
{ verb: "DELETE", unirestMethod: "delete" },
{ verb: "HEAD", unirestMethod: "head" },
{ verb: "OPTIONS", unirestMethod: "options" },
]
// create client and request
const verb = verbs.find((v) => v.verb === method)
const unirestMethod = verb.unirestMethod || "get"
requestString.push(
`HttpResponse<String> response = Unirest.${unirestMethod}("${url}${pathName}?${queryString}")\n`
)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
requestString.push(
`.header("authorization", "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}") \n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(`.header("authorization", "Bearer ${bearerToken}") \n`)
}
// custom headers
if (headers) {
headers.forEach(({ key, value }) => {
if (key) {
requestString.push(`.header("${key}", "${value}")\n`)
}
})
}
// set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
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(`.asString();\n`)
return requestString.join("")
},
}

View File

@@ -1,68 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const JavascriptFetchCodegen = {
id: "js-fetch",
name: "JavaScript Fetch",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
let genHeaders = []
requestString.push(`fetch("${url}${pathName}?${queryString}", {\n`)
requestString.push(` method: "${method}",\n`)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
if (contentType && requestBody) {
if (isJSONContentType(contentType)) {
requestBody = `JSON.stringify(${requestBody})`
} else if (contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
}
}
if (requestBody) {
requestString.push(` body: ${requestBody},\n`)
}
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
genHeaders = genHeaders.join("").slice(0, -2)
if (genHeaders) {
requestString.push(` headers: {\n${genHeaders}\n },\n`)
}
requestString.push(' credentials: "same-origin"\n')
requestString.push("}).then(function(response) {\n")
requestString.push(" return response.text()\n")
requestString.push("}).catch(function(e) {\n")
requestString.push(" console.error(e)\n")
requestString.push("})")
return requestString.join("")
},
}

View File

@@ -1,66 +0,0 @@
export const JavascriptJqueryCodegen = {
id: "js-jquery",
name: "JavaScript jQuery",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
contentType,
rawRequestBody,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(
`jQuery.ajax({\n url: "${url}${pathName}?${queryString}"`
)
requestString.push(`,\n method: "${method.toUpperCase()}"`)
let requestBody = rawInput ? rawParams : rawRequestBody
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 }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\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")
requestString.push(" console.error(e);\n")
requestString.push("})\n")
return requestString.join("")
},
}

View File

@@ -1,60 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const JavascriptXhrCodegen = {
id: "js-xhr",
name: "JavaScript XHR",
language: "javascript",
generator: ({
auth,
httpUser,
httpPassword,
method,
url,
pathName,
queryString,
bearerToken,
headers,
rawInput,
rawParams,
rawRequestBody,
contentType,
}) => {
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
requestString.push(
`xhr.open('${method}', '${url}${pathName}?${queryString}', true, ${user}, ${password})`
)
if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(
`xhr.setRequestHeader('Authorization', 'Bearer ${bearerToken}')`
)
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key)
requestString.push(`xhr.setRequestHeader('${key}', '${value}')`)
})
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
if (contentType && requestBody) {
if (isJSONContentType(contentType)) {
requestBody = `JSON.stringify(${requestBody})`
} else if (contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
}
}
requestBody = requestBody || ""
requestString.push(`xhr.send(${requestBody})`)
} else {
requestString.push("xhr.send()")
}
return requestString.join("\n")
},
}

View File

@@ -1,73 +0,0 @@
export const NodejsAxiosCodegen = {
id: "nodejs-axios",
name: "NodeJs Axios",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
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 && requestBody.length !== 0) {
requestString.push(", ")
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(`\n "${key}": "${value}",`)
})
}
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\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")
requestString.push(" console.error(e);\n")
requestString.push("})\n")
return requestString.join("")
},
}

View File

@@ -1,82 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const NodejsNativeCodegen = {
id: "nodejs-native",
name: "NodeJs Native",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(`const http = require('http');\n\n`)
requestString.push(`const url = '${url}${pathName}?${queryString}';\n`)
requestString.push(`const options = {\n`)
requestString.push(` method: '${method}',\n`)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
}
let requestBody
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
requestBody = rawInput ? rawParams : rawRequestBody
if (isJSONContentType(contentType) && requestBody) {
requestBody = `JSON.stringify(${requestBody})`
} else if (requestBody) {
requestBody = `\`${requestBody}\``
}
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
if (genHeaders.length > 0 || headers.length > 0) {
requestString.push(
` headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n`
)
}
requestString.push(`};\n\n`)
requestString.push(
`const request = http.request(url, options, (response) => {\n`
)
requestString.push(` console.log(response);\n`)
requestString.push(`});\n\n`)
requestString.push(`request.on('error', (e) => {\n`)
requestString.push(` console.error(e);\n`)
requestString.push(`});\n`)
if (requestBody) {
requestString.push(`\nrequest.write(${requestBody});\n`)
}
requestString.push(`request.end();`)
return requestString.join("")
},
}

View File

@@ -1,87 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const NodejsRequestCodegen = {
id: "nodejs-request",
name: "NodeJs Request",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(`const request = require('request');\n`)
requestString.push(`const options = {\n`)
requestString.push(` method: '${method.toLowerCase()}',\n`)
requestString.push(` url: '${url}${pathName}?${queryString}'`)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
let reqBodyType = "formData"
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 (requestBody) {
requestString.push(`,\n ${reqBodyType}: ${requestBody}`)
}
}
if (headers.length > 0) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
if (genHeaders.length > 0 || headers.length > 0) {
requestString.push(
`,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }`
)
}
requestString.push(`\n}`)
requestString.push(`\nrequest(options, (error, response) => {\n`)
requestString.push(` if (error) throw new Error(error);\n`)
requestString.push(` console.log(response.body);\n`)
requestString.push(`});`)
return requestString.join("")
},
}

View File

@@ -1,87 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const NodejsUnirestCodegen = {
id: "nodejs-unirest",
name: "NodeJs Unirest",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(`const unirest = require('unirest');\n`)
requestString.push(`const req = unirest(\n`)
requestString.push(
`'${method.toLowerCase()}', '${url}${pathName}?${queryString}')\n`
)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
let reqBodyType = "formData"
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 (requestBody) {
requestString.push(`\n.${reqBodyType}( ${requestBody})`)
}
}
if (headers.length > 0) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
if (genHeaders.length > 0 || headers.length > 0) {
requestString.push(
`\n.headers({\n${genHeaders.join("").slice(0, -2)}\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`)
return requestString.join("")
},
}

View File

@@ -1,99 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
export const PhpCurlCodegen = {
id: "php-curl",
name: "PHP cURL",
language: "php",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(`<?php\n`)
requestString.push(`$curl = curl_init();\n`)
requestString.push(`curl_setopt_array($curl, array(\n`)
requestString.push(` CURLOPT_URL => "${url}${pathName}?${queryString}",\n`)
requestString.push(` CURLOPT_RETURNTRANSFER => true,\n`)
requestString.push(` CURLOPT_ENCODING => "",\n`)
requestString.push(` CURLOPT_MAXREDIRS => 10,\n`)
requestString.push(` CURLOPT_TIMEOUT => 0,\n`)
requestString.push(` CURLOPT_FOLLOWLOCATION => true,\n`)
requestString.push(` CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,\n`)
requestString.push(` CURLOPT_CUSTOMREQUEST => "${method}",\n`)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` "Authorization: Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` "Authorization: Bearer ${bearerToken}",\n`)
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
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 (headers.length > 0) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}: ${value}",\n`)
})
}
if (genHeaders.length > 0 || headers.length > 0) {
requestString.push(
` CURLOPT_HTTPHEADER => array(\n${genHeaders
.join("")
.slice(0, -2)}\n )\n`
)
}
requestString.push(`));\n`)
requestString.push(`$response = curl_exec($curl);\n`)
requestString.push(`curl_close($curl);\n`)
requestString.push(`echo $response;\n`)
return requestString.join("")
},
}

View File

@@ -1,63 +0,0 @@
export const PowershellRestmethodCodegen = {
id: "powershell-restmethod",
name: "PowerShell RestMethod",
language: "powershell",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
headers,
}) => {
const methodsWithBody = ["Put", "Post", "Delete"]
const formattedMethod =
method[0].toUpperCase() + method.substring(1).toLowerCase()
const includeBody = methodsWithBody.includes(formattedMethod)
const requestString = []
let genHeaders = []
let variables = ""
requestString.push(
`Invoke-RestMethod -Method '${formattedMethod}' -Uri '${url}${pathName}?${queryString}'`
)
const requestBody = rawInput ? rawParams : rawRequestBody
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 }) => {
if (key) genHeaders.push(` '${key}' = '${value}'\n`)
})
}
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
` 'Authorization' = 'Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}'\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(` 'Authorization' = 'Bearer ${bearerToken}'\n`)
}
genHeaders = genHeaders.join("").slice(0, -1)
if (genHeaders) {
variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`)
requestString.push(` -Headers $headers`)
}
if (requestBody && includeBody) {
requestString.push(` -Body $body`)
}
return `${variables}${requestString.join("")}`
},
}

View File

@@ -1,105 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
const printHeaders = (headers) => {
if (headers.length) {
return [`headers = {\n`, ` ${headers.join(",\n ")}\n`, `}\n`]
} else {
return [`headers = {}\n`]
}
}
export const PythonHttpClientCodegen = {
id: "python-http-client",
name: "Python http.client",
language: "python",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(`import http.client\n`)
requestString.push(`import mimetypes\n`)
const currentUrl = new URL(url)
const hostname = currentUrl.hostname
const port = currentUrl.port
if (!port) {
requestString.push(`conn = http.client.HTTPSConnection("${hostname}")\n`)
} else {
requestString.push(
`conn = http.client.HTTPSConnection("${hostname}", ${port})\n`
)
}
// auth headers
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
`'Authorization': 'Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}'`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(`'Authorization': 'Bearer ${bearerToken}'`)
}
// custom headers
if (headers.length) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(`'${key}': '${value}'`)
})
}
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
if (method === "GET") {
requestString.push(...printHeaders(genHeaders))
requestString.push(`payload = ''\n`)
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
requestString.push(...printHeaders(genHeaders))
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(`payload = ''\n`)
}
}
requestString.push(
`conn.request("${method}", "${pathName}?${queryString}", payload, headers)\n`
)
requestString.push(`res = conn.getresponse()\n`)
requestString.push(`data = res.read()\n`)
requestString.push(`print(data.decode("utf-8"))`)
return requestString.join("")
},
}

View File

@@ -1,102 +0,0 @@
import { isJSONContentType } from "~/helpers/utils/contenttypes"
const printHeaders = (headers) => {
if (headers.length) {
return [`headers = {\n`, ` ${headers.join(",\n ")}\n`, `}\n`]
}
return []
}
export const PythonRequestsCodegen = {
id: "python-requests",
name: "Python Requests",
language: "python",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(`import requests\n\n`)
requestString.push(`url = '${url}${pathName}?${queryString}'\n`)
// auth headers
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
genHeaders.push(
`'Authorization': 'Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}'`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
genHeaders.push(`'Authorization': 'Bearer ${bearerToken}'`)
}
// custom headers
if (headers.length) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(`'${key}': '${value}'`)
})
}
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
let requestDataObj = ""
requestString.push(...printHeaders(genHeaders))
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 (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`)
}
if (genHeaders.length) {
requestString.push(` headers=headers,\n`)
}
requestString.push(`)\n\n`)
requestString.push(`print(response)`)
return requestString.join("")
},
}

View File

@@ -1,80 +0,0 @@
export const RubyNetHttpCodeGen = {
id: "ruby-net-http",
name: "Ruby Net::HTTP",
language: "ruby",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
headers,
}) => {
const requestString = []
requestString.push(`require 'net/http'\n`)
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
if (requestBody) {
requestBody = requestBody.replaceAll(/'/g, "\\'") // escape single-quotes for single-quoted string compatibility
}
const verbs = [
{ verb: "GET", rbMethod: "Get" },
{ verb: "POST", rbMethod: "Post" },
{ verb: "PUT", rbMethod: "Put" },
{ verb: "PATCH", rbMethod: "Patch" },
{ verb: "DELETE", rbMethod: "Delete" },
]
// 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)`)
// custom headers
if (headers) {
headers.forEach(({ key, value }) => {
if (key) {
requestString.push(`request['${key}'] = '${value}'`)
}
})
}
// authentication
if (auth === "Basic Auth") {
requestString.push(`request.basic_auth('${httpUser}', '${httpPassword}')`)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(`request['Authorization'] = 'Bearer ${bearerToken}'`)
}
// set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push(`request.body = '${requestBody}'\n`)
}
// process
requestString.push(`http = Net::HTTP.new(uri.host, uri.port)`)
requestString.push(`http.use_ssl = uri.is_a?(URI::HTTPS)`)
requestString.push(`response = http.request(request)\n`)
// analyse result
requestString.push(`unless response.is_a?(Net::HTTPSuccess) then`)
requestString.push(
` raise "An error occurred: #{response.code} #{response.message}"`
)
requestString.push(`else`)
requestString.push(` puts response.body`)
requestString.push(`end`)
return requestString.join("\n")
},
}

View File

@@ -1,80 +0,0 @@
export const SalesforceApexCodegen = {
id: "salesforce-apex",
name: "Salesforce Apex",
language: "apex",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
headers,
}) => {
const requestString = []
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
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`)
requestString.push(`request.setMethod('${method}');\n`)
requestString.push(
`request.setEndpoint('${url}${pathName}?${queryString}');\n\n`
)
// authentification
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
requestString.push(
`request.setHeader('Authorization', 'Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}');\n`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(
`request.setHeader('Authorization', 'Bearer ${bearerToken}');\n`
)
}
// custom headers
if (headers) {
headers.forEach(({ key, value }) => {
if (key) {
requestString.push(`request.setHeader('${key}', '${value}');\n`)
}
})
}
requestString.push(`\n`)
// set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push(`request.setBody('${requestBody}');\n\n`)
}
// process
requestString.push(`try {\n`)
requestString.push(` Http client = new Http();\n`)
requestString.push(` HttpResponse response = client.send(request);\n`)
requestString.push(` System.debug(response.getBody());\n`)
requestString.push(`} catch (CalloutException ex) {\n`)
requestString.push(
` System.debug('An error occurred ' + ex.getMessage());\n`
)
requestString.push(`}`)
return requestString.join("")
},
}

View File

@@ -1,58 +0,0 @@
export const ShellHttpieCodegen = {
id: "shell-httpie",
name: "Shell HTTPie",
language: "sh",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
headers,
}) => {
const methodsWithBody = ["POST", "PUT", "PATCH", "DELETE"]
const includeBody = methodsWithBody.includes(method)
const requestString = []
let requestBody = rawInput ? rawParams : rawRequestBody
if (requestBody && includeBody) {
requestBody = requestBody.replace(/'/g, "\\'")
// Send request body via redirected input
requestString.push(`echo -n $'${requestBody}' | `)
}
// Executable itself
requestString.push(`http`)
// basic authentication
if (auth === "Basic Auth") {
requestString.push(` -a ${httpUser}:${httpPassword}`)
}
// URL
let escapedUrl = `${url}${pathName}?${queryString}`
escapedUrl = escapedUrl.replace(/'/g, "\\'")
requestString.push(` ${method} $'${escapedUrl}'`)
if (headers) {
headers.forEach(({ key, value }) => {
requestString.push(
` $'${key.replace(/'/g, "\\'")}:${value.replace(/'/g, "\\'")}'`
)
})
}
if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(` 'Authorization:Bearer ${bearerToken}'`)
}
return requestString.join("")
},
}

View File

@@ -1,43 +0,0 @@
export const ShellWgetCodegen = {
id: "shell-wget",
name: "Shell wget",
language: "sh",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
headers,
}) => {
const requestString = []
const requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(`wget -O - --method=${method}`)
requestString.push(` '${url}${pathName}?${queryString}'`)
if (auth === "Basic Auth") {
const basic = `${httpUser}:${httpPassword}`
requestString.push(
` --header='Authorization: Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}'`
)
} else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
requestString.push(` --header='Authorization: Bearer ${bearerToken}'`)
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) requestString.push(` --header='${key}: ${value}'`)
})
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
requestString.push(` --body-data='${requestBody}'`)
}
return requestString.join(" \\\n")
},
}