nodejs-request.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 (isJSONContentType(contentType)) {
  41. requestBody = `JSON.stringify(${requestBody})`
  42. reqBodyType = "body"
  43. } else if (contentType.includes("x-www-form-urlencoded")) {
  44. const formData = []
  45. if (requestBody.includes("=")) {
  46. requestBody.split("&").forEach((rq) => {
  47. const [key, val] = rq.split("=")
  48. formData.push(`"${key}": "${val}"`)
  49. })
  50. }
  51. if (formData.length) {
  52. requestBody = `{${formData.join(", ")}}`
  53. }
  54. reqBodyType = "form"
  55. } else if (contentType.includes("application/xml")) {
  56. requestBody = `\`${requestBody}\``
  57. reqBodyType = "body"
  58. }
  59. if (contentType) {
  60. genHeaders.push(
  61. ` "Content-Type": "${contentType}; charset=utf-8",\n`
  62. )
  63. }
  64. requestString.push(`,\n ${reqBodyType}: ${requestBody}`)
  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}`)
  77. requestString.push(`\nrequest(options, (error, response) => {\n`)
  78. requestString.push(` if (error) throw new Error(error);\n`)
  79. requestString.push(` console.log(response.body);\n`)
  80. requestString.push(`});`)
  81. return requestString.join("")
  82. },
  83. }