nodejs-native.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const NodejsNativeCodegen = {
  3. id: "nodejs-native",
  4. name: "NodeJs Native",
  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 http = require('http');\n\n`)
  24. requestString.push(`const url = '${url}${pathName}?${queryString}';\n`)
  25. requestString.push(`const options = {\n`)
  26. requestString.push(` method: '${method}',\n`)
  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. let requestBody
  38. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  39. requestBody = rawInput ? rawParams : rawRequestBody
  40. if (isJSONContentType(contentType)) {
  41. requestBody = `JSON.stringify(${requestBody})`
  42. } else {
  43. requestBody = `\`${requestBody}\``
  44. }
  45. if (contentType) {
  46. genHeaders.push(
  47. ` "Content-Type": "${contentType}; charset=utf-8",\n`
  48. )
  49. }
  50. }
  51. if (headers) {
  52. headers.forEach(({ key, value }) => {
  53. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  54. })
  55. }
  56. if (genHeaders.length > 0 || headers.length > 0) {
  57. requestString.push(
  58. ` headers: {\n${genHeaders.join("").slice(0, -2)}\n }`
  59. )
  60. }
  61. requestString.push(`};\n\n`)
  62. requestString.push(
  63. `const request = http.request(url, options, (response) => {\n`
  64. )
  65. requestString.push(` console.log(response);\n`)
  66. requestString.push(`});\n\n`)
  67. requestString.push(`request.on('error', (e) => {\n`)
  68. requestString.push(` console.error(e);\n`)
  69. requestString.push(`});\n`)
  70. if (requestBody) {
  71. requestString.push(`\nrequest.write(${requestBody});\n`)
  72. }
  73. requestString.push(`request.end();`)
  74. return requestString.join("")
  75. },
  76. }