nodejs-unirest.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const NodejsUnirestCodegen = {
  3. id: "nodejs-unirest",
  4. name: "NodeJs Unirest",
  5. language: "javascript",
  6. generator: ({
  7. url,
  8. pathName,
  9. queryString,
  10. auth,
  11. httpUser,
  12. httpPassword,
  13. bearerToken,
  14. method,
  15. rawInput,
  16. rawParams,
  17. rawRequestBody,
  18. contentType,
  19. headers,
  20. }) => {
  21. const requestString = []
  22. const genHeaders = []
  23. requestString.push(`const unirest = require('unirest');\n`)
  24. requestString.push(`const req = unirest(\n`)
  25. requestString.push(
  26. `'${method.toLowerCase()}', '${url}${pathName}?${queryString}')\n`
  27. )
  28. if (auth === "Basic Auth") {
  29. const basic = `${httpUser}:${httpPassword}`
  30. genHeaders.push(
  31. ` "Authorization": "Basic ${window.btoa(
  32. unescape(encodeURIComponent(basic))
  33. )}",\n`
  34. )
  35. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  36. genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
  37. }
  38. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  39. let requestBody = rawInput ? rawParams : rawRequestBody
  40. let reqBodyType = "formData"
  41. if (isJSONContentType(contentType)) {
  42. requestBody = `\`${requestBody}\``
  43. reqBodyType = "send"
  44. } else if (contentType.includes("x-www-form-urlencoded")) {
  45. const formData = []
  46. if (requestBody.includes("=")) {
  47. requestBody.split("&").forEach((rq) => {
  48. const [key, val] = rq.split("=")
  49. formData.push(`"${key}": "${val}"`)
  50. })
  51. }
  52. if (formData.length) {
  53. requestBody = `{${formData.join(", ")}}`
  54. }
  55. reqBodyType = "send"
  56. } else if (contentType.includes("application/xml")) {
  57. requestBody = `\`${requestBody}\``
  58. reqBodyType = "send"
  59. }
  60. if (contentType) {
  61. genHeaders.push(
  62. ` "Content-Type": "${contentType}; charset=utf-8",\n`
  63. )
  64. }
  65. requestString.push(`.\n ${reqBodyType}( ${requestBody})`)
  66. }
  67. if (headers.length > 0) {
  68. headers.forEach(({ key, value }) => {
  69. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  70. })
  71. }
  72. if (genHeaders.length > 0 || headers.length > 0) {
  73. requestString.push(
  74. `.\n headers({\n${genHeaders.join("").slice(0, -2)}\n }`
  75. )
  76. }
  77. requestString.push(`\n)`)
  78. requestString.push(`\n.end(function (res) {\n`)
  79. requestString.push(` if (res.error) throw new Error(res.error);\n`)
  80. requestString.push(` console.log(res.raw_body);\n });\n`)
  81. return requestString.join("")
  82. },
  83. }