refactor: monorepo+pnpm (removed husky)

This commit is contained in:
Andrew Bastin
2021-09-10 00:28:28 +05:30
parent 917550ff4d
commit b28f82a881
445 changed files with 81301 additions and 63752 deletions

View File

@@ -0,0 +1,73 @@
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;`)
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}");`
)
}
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
let requestBody = rawInput ? rawParams : rawRequestBody
if (contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
} else requestBody = JSON.stringify(requestBody)
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);")
requestString.push(`CURLcode ret = curl_easy_perform(hnd);`)
return requestString.join("\n")
},
}

View File

@@ -0,0 +1,103 @@
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
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`
)
}
// content type
if (contentType) {
requestString.push(
`request.AddHeader("Content-Type", "${contentType}");\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)) {
requestString.push(
`request.AddParameter("${requestContentType}", @"${requestBody}", ParameterType.RequestBody);\n\n`
)
}
// process
const verb = verbs.find((v) => v.verb === method)
requestString.push(`var response = client.${verb.csMethod}(request);\n\n`)
// 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

@@ -0,0 +1,45 @@
export const CurlCodegen = {
id: "curl",
name: "cURL",
language: "sh",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
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)) {
const requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(` -H 'Content-Type: ${contentType}; charset=utf-8'`)
requestString.push(` -d '${requestBody}'`)
}
return requestString.join(" \\\n")
},
}

View File

@@ -0,0 +1,82 @@
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 (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`)
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`
)
}
}
// 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

@@ -0,0 +1,73 @@
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.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
} else requestBody = JSON.stringify(requestBody)
requestString.push(
`MediaType mediaType = MediaType.parse("${contentType}");`
)
requestString.push(
`RequestBody body = RequestBody.create(mediaType,${requestBody});`
)
}
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

@@ -0,0 +1,72 @@
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)
requestString.push(
`HttpResponse<String> response = Unirest.${verb.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`)
}
})
}
if (contentType) {
requestString.push(`.header("Content-Type", "${contentType}")\n`)
}
// set body
if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
if (contentType.includes("x-www-form-urlencoded")) {
requestBody = `"${requestBody}"`
} else {
requestBody = JSON.stringify(requestBody)
}
requestString.push(`.body(${requestBody})`)
}
requestString.push(`\n.asString();\n`)
return requestString.join("")
},
}

View File

@@ -0,0 +1,66 @@
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 (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 (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
genHeaders = genHeaders.join("").slice(0, -2)
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")
requestString.push("})")
return requestString.join("")
},
}

View File

@@ -0,0 +1,64 @@
export const JavascriptJqueryCodegen = {
id: "js-jquery",
name: "JavaScript jQuery",
language: "javascript",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
const genHeaders = []
requestString.push(
`jQuery.ajax({\n url: "${url}${pathName}${queryString}"`
)
requestString.push(`,\n method: "${method.toUpperCase()}"`)
const requestBody = rawInput ? rawParams : rawRequestBody
if (requestBody.length !== 0) {
requestString.push(`,\n body: ${requestBody}`)
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
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(
` "Authorization": "Basic ${window.btoa(
unescape(encodeURIComponent(basic))
)}",\n`
)
} 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")
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

@@ -0,0 +1,57 @@
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()")
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 (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')`
)
requestString.push(`xhr.send(${requestBody})`)
} else {
requestString.push("xhr.send()")
}
return requestString.join("\n")
},
}

View File

@@ -0,0 +1,59 @@
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 = []
const requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(
`axios.${method.toLowerCase()}('${url}${pathName}${queryString}'`
)
if (requestBody.length !== 0) {
requestString.push(", ")
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` "${key}": "${value}",\n`)
})
}
if (contentType) {
genHeaders.push(`"Content-Type": "${contentType}; charset=utf-8",\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`)
}
requestString.push(
`${requestBody},{ \n headers : {${genHeaders.join("").slice(0, -2)}}\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

@@ -0,0 +1,87 @@
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 = `JSON.stringify(${requestBody})`
} else {
requestBody = `\`${requestBody}\``
}
if (contentType) {
genHeaders.push(
` "Content-Type": "${contentType}; charset=utf-8",\n`
)
}
}
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 }`
)
}
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

@@ -0,0 +1,88 @@
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 (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 (contentType) {
genHeaders.push(
` "Content-Type": "${contentType}; charset=utf-8",\n`
)
}
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

@@ -0,0 +1,89 @@
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 (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 (contentType) {
genHeaders.push(
` "Content-Type": "${contentType}; charset=utf-8",\n`
)
}
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(`\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

@@ -0,0 +1,97 @@
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 (
!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].toString()}`)
.join("&")}"`
}
}
if (contentType) {
genHeaders.push(` "Content-Type: ${contentType}; charset=utf-8",\n`)
}
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

@@ -0,0 +1,65 @@
export const PowershellRestmethodCodegen = {
id: "powershell-restmethod",
name: "PowerShell RestMethod",
language: "powershell",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
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 (requestBody.length !== 0 && includeBody) {
variables = variables.concat(`$body = @'\n${requestBody}\n'@\n\n`)
}
if (headers) {
headers.forEach(({ key, value }) => {
if (key) genHeaders.push(` '${key}' = '${value}'\n`)
})
}
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(
` '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)
variables = variables.concat(`$headers = @{\n${genHeaders}\n}\n`)
requestString.push(` -Headers $headers`)
if (includeBody) {
requestString.push(` -Body $body`)
}
return `${variables}\n${requestString.join("")}`
},
}

View File

@@ -0,0 +1,102 @@
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)) {
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`)
}
} else {
requestString.push(`paylod = '''${requestBody}'''\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

@@ -0,0 +1,99 @@
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
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))
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`)
}
} else {
requestString.push(`data = '''${requestBody}'''\n`)
}
requestString.push(`response = requests.request(\n`)
requestString.push(` '${method}',\n`)
requestString.push(` '${url}${pathName}${queryString}',\n`)
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

@@ -0,0 +1,83 @@
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,
contentType,
headers,
}) => {
const requestString = []
requestString.push(`require 'net/http'\n`)
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
requestBody = requestBody.replace(/'/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)
requestString.push(`uri = URI.parse('${url}${pathName}${queryString}')\n`)
requestString.push(`request = Net::HTTP::${verb.rbMethod}.new(uri)`)
// content type
if (contentType) {
requestString.push(`request['Content-Type'] = '${contentType}'`)
}
// custom headers
if (headers) {
headers.forEach(({ key, value }) => {
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)) {
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

@@ -0,0 +1,86 @@
export const SalesforceApexCodegen = {
id: "salesforce-apex",
name: "Salesforce Apex",
language: "apex",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
// initial request setup
let requestBody = rawInput ? rawParams : rawRequestBody
requestBody = JSON.stringify(requestBody)
.replace(/^"|"$/g, "")
.replace(/\\"/g, '"')
.replace(/'/g, "\\'") // Apex uses single quotes for strings
// 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`
)
}
// content type
if (contentType) {
requestString.push(
`request.setHeader('Content-Type', '${contentType}');\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)) {
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

@@ -0,0 +1,63 @@
export const ShellHttpieCodegen = {
id: "shell-httpie",
name: "Shell HTTPie",
language: "sh",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const methodsWithBody = ["POST", "PUT", "PATCH", "DELETE"]
const includeBody = methodsWithBody.includes(method)
const requestString = []
let requestBody = rawInput ? rawParams : rawRequestBody
requestBody = requestBody.replace(/'/g, "\\'")
if (requestBody.length !== 0 && includeBody) {
// 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}'`)
// All headers
if (contentType) {
requestString.push(` 'Content-Type:${contentType}; charset=utf-8'`)
}
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

@@ -0,0 +1,47 @@
export const ShellWgetCodegen = {
id: "shell-wget",
name: "Shell wget",
language: "sh",
generator: ({
url,
pathName,
queryString,
auth,
httpUser,
httpPassword,
bearerToken,
method,
rawInput,
rawParams,
rawRequestBody,
contentType,
headers,
}) => {
const requestString = []
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)) {
const requestBody = rawInput ? rawParams : rawRequestBody
requestString.push(
` --header='Content-Type: ${contentType}; charset=utf-8'`
)
requestString.push(` --body-data='${requestBody}'`)
}
return requestString.join(" \\\n")
},
}