nodejs-native.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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) && requestBody) {
  41. requestBody = `JSON.stringify(${requestBody})`
  42. } else if (requestBody) {
  43. requestBody = `\`${requestBody}\``
  44. }
  45. }
  46. if (headers) {
  47. headers.forEach(({ key, value }) => {
  48. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  49. })
  50. }
  51. if (genHeaders.length > 0 || headers.length > 0) {
  52. requestString.push(
  53. ` headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n`
  54. )
  55. }
  56. requestString.push(`};\n\n`)
  57. requestString.push(
  58. `const request = http.request(url, options, (response) => {\n`
  59. )
  60. requestString.push(` console.log(response);\n`)
  61. requestString.push(`});\n\n`)
  62. requestString.push(`request.on('error', (e) => {\n`)
  63. requestString.push(` console.error(e);\n`)
  64. requestString.push(`});\n`)
  65. if (requestBody) {
  66. requestString.push(`\nrequest.write(${requestBody});\n`)
  67. }
  68. requestString.push(`request.end();`)
  69. return requestString.join("")
  70. },
  71. }