nodejs-request.js 2.6 KB

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