nodejs-unirest.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 (contentType && requestBody) {
  42. if (isJSONContentType(contentType)) {
  43. requestBody = `\`${requestBody}\``
  44. reqBodyType = "send"
  45. } else if (contentType.includes("x-www-form-urlencoded")) {
  46. const formData = []
  47. if (requestBody.includes("=")) {
  48. requestBody.split("&").forEach((rq) => {
  49. const [key, val] = rq.split("=")
  50. formData.push(`"${key}": "${val}"`)
  51. })
  52. }
  53. if (formData.length) {
  54. requestBody = `{${formData.join(", ")}}`
  55. }
  56. reqBodyType = "send"
  57. } else if (contentType.includes("application/xml")) {
  58. requestBody = `\`${requestBody}\``
  59. reqBodyType = "send"
  60. }
  61. }
  62. if (requestBody) {
  63. requestString.push(`\n.${reqBodyType}( ${requestBody})`)
  64. }
  65. }
  66. if (headers.length > 0) {
  67. headers.forEach(({ key, value }) => {
  68. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  69. })
  70. }
  71. if (genHeaders.length > 0 || headers.length > 0) {
  72. requestString.push(
  73. `\n.headers({\n${genHeaders.join("").slice(0, -2)}\n })`
  74. )
  75. }
  76. requestString.push(`\n.end(function (res) {\n`)
  77. requestString.push(` if (res.error) throw new Error(res.error);\n`)
  78. requestString.push(` console.log(res.raw_body);\n });\n`)
  79. return requestString.join("")
  80. },
  81. }