nodejs-unirest.js 2.5 KB

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