Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
[#1190] [Jyoti] Add codegen for nodeJs Unirest support (#1308)
Jyoti Gupta846298210a05
diff --git a/helpers/codegen/__tests__/__snapshots__/codegen.spec.js.snap b/helpers/codegen/__tests__/__snapshots__/codegen.spec.js.snapindex 87b38c4ef..cb2602c3a 100644--- a/helpers/codegen/__tests__/__snapshots__/codegen.spec.js.snap+++ b/helpers/codegen/__tests__/__snapshots__/codegen.spec.js.snap@@ -755,6 +755,84 @@ request(options, (error, response) => {});"`;+exports[`generate request for NodeJs Unirest generate GET request 1`] = `+"const unirest = require('unirest');+const req = unirest(+'get', 'https://httpbin.org/path/to?a=b')+.+ headers({+ \\"Authorization\\": \\"Basic bW9ja1VzZXI6bW9ja1Bhc3N3b3Jk\\",+ \\"h1\\": \\"h1v\\",+ \\"h2\\": \\"h2v\\"+ }+)+.end(function (res) {+ if (res.error) throw new Error(res.error);+ console.log(res.raw_body);+ });+"+`;++exports[`generate request for NodeJs Unirest generate POST request for JSON 1`] = `+"const unirest = require('unirest');+const req = unirest(+'post', 'https://httpbin.org/path/to?a=b')+.+ send( \`{\\"foo\\": \\"bar\\", \\"baz\\": \\"qux\\"}\`).+ headers({+ \\"Authorization\\": \\"Bearer abcdefghijklmn\\",+ \\"Content-Type\\": \\"application/json; charset=utf-8\\",+ \\"h1\\": \\"h1v\\",+ \\"h2\\": \\"h2v\\"+ }+)+.end(function (res) {+ if (res.error) throw new Error(res.error);+ console.log(res.raw_body);+ });+"+`;++exports[`generate request for NodeJs Unirest generate POST request for XML 1`] = `+"const unirest = require('unirest');+const req = unirest(+'post', 'https://httpbin.org/path/to?a=b')+.+ send( \`<?xml version='1.0' encoding='utf-8'?>+<xml>+ <element foo=\\"bar\\"></element>+</xml>\`).+ headers({+ \\"Authorization\\": \\"Bearer abcdefghijklmn\\",+ \\"Content-Type\\": \\"application/xml; charset=utf-8\\",+ \\"h1\\": \\"h1v\\",+ \\"h2\\": \\"h2v\\"+ }+)+.end(function (res) {+ if (res.error) throw new Error(res.error);+ console.log(res.raw_body);+ });+"+`;++exports[`generate request for NodeJs Unirest generate PUT request for www-form-urlencoded 1`] = `+"const unirest = require('unirest');+const req = unirest(+'put', 'https://httpbin.org/path/to?a=b')+.+ send( {\\"foo\\": \\"bar\\", \\"baz\\": \\"qux\\"}).+ headers({+ \\"Content-Type\\": \\"application/x-www-form-urlencoded; charset=utf-8\\"+ }+)+.end(function (res) {+ if (res.error) throw new Error(res.error);+ console.log(res.raw_body);+ });+"+`;+exports[`generate request for PHP cURL generate GET request 1`] = `<?php$curl = curl_init();diff --git a/helpers/codegen/codegen.js b/helpers/codegen/codegen.jsindex ebf460270..34701f294 100644--- a/helpers/codegen/codegen.js+++ b/helpers/codegen/codegen.js@@ -10,6 +10,7 @@ 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"@@ -40,6 +41,7 @@ export const codegens = [NodejsAxiosCodegen,NodejsNativeCodegen,NodejsRequestCodegen,+ NodejsUnirestCodegen,PhpCurlCodegen,PowershellRestmethodCodegen,PythonHttpClientCodegen,diff --git a/helpers/codegen/generators/nodejs-unirest.js b/helpers/codegen/generators/nodejs-unirest.jsnew file mode 100644index 000000000..f92eb9f19--- /dev/null+++ b/helpers/codegen/generators/nodejs-unirest.js@@ -0,0 +1,80 @@+import { isJSONContentType } from "~/helpers/utils/contenttypes"++export const NodejsUnirestCodegen = {+ id: "nodejs-unirest",+ name: "NodeJs Unirest",+ generator: ({+ url,+ pathName,+ queryString,+ auth,+ httpUser,+ httpPassword,+ bearerToken,+ method,+ rawInput,+ rawParams,+ rawRequestBody,+ contentType,+ headers,+ }) => {+ const requestString = []+ let 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("")+ },+}