nodejs-request.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const NodejsRequestCodegen = {
  3. id: "nodejs-request",
  4. name: "NodeJs Request",
  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 request = require('request');\n`)
  24. requestString.push(`const options = {\n`)
  25. requestString.push(` method: '${method.toLowerCase()}',\n`)
  26. requestString.push(` url: '${url}${pathName}?${queryString}'`)
  27. if (auth === "Basic Auth") {
  28. const basic = `${httpUser}:${httpPassword}`
  29. genHeaders.push(
  30. ` "Authorization": "Basic ${window.btoa(
  31. unescape(encodeURIComponent(basic))
  32. )}",\n`
  33. )
  34. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  35. genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
  36. }
  37. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  38. let requestBody = rawInput ? rawParams : rawRequestBody
  39. let reqBodyType = "formData"
  40. if (contentType && requestBody) {
  41. if (isJSONContentType(contentType)) {
  42. requestBody = `JSON.stringify(${requestBody})`
  43. reqBodyType = "body"
  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 = "form"
  56. } else if (contentType.includes("application/xml")) {
  57. requestBody = `\`${requestBody}\``
  58. reqBodyType = "body"
  59. }
  60. }
  61. if (requestBody) {
  62. requestString.push(`,\n ${reqBodyType}: ${requestBody}`)
  63. }
  64. }
  65. if (headers.length > 0) {
  66. headers.forEach(({ key, value }) => {
  67. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  68. })
  69. }
  70. if (genHeaders.length > 0 || headers.length > 0) {
  71. requestString.push(
  72. `,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }`
  73. )
  74. }
  75. requestString.push(`\n}`)
  76. requestString.push(`\nrequest(options, (error, response) => {\n`)
  77. requestString.push(` if (error) throw new Error(error);\n`)
  78. requestString.push(` console.log(response.body);\n`)
  79. requestString.push(`});`)
  80. return requestString.join("")
  81. },
  82. }