nodejs-axios.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. export const NodejsAxiosCodegen = {
  2. id: "nodejs-axios",
  3. name: "NodeJs Axios",
  4. language: "javascript",
  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. const genHeaders = []
  22. let requestBody = rawInput ? rawParams : rawRequestBody
  23. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  24. if (
  25. contentType &&
  26. contentType.includes("x-www-form-urlencoded") &&
  27. requestBody
  28. ) {
  29. requestString.push(
  30. `var params = new URLSearchParams("${requestBody}")\n`
  31. )
  32. requestBody = "params"
  33. }
  34. }
  35. requestString.push(
  36. `axios.${method.toLowerCase()}('${url}${pathName}?${queryString}'`
  37. )
  38. if (requestBody && requestBody.length !== 0) {
  39. requestString.push(", ")
  40. }
  41. if (headers) {
  42. headers.forEach(({ key, value }) => {
  43. if (key) genHeaders.push(`\n "${key}": "${value}",`)
  44. })
  45. }
  46. if (auth === "Basic Auth") {
  47. const basic = `${httpUser}:${httpPassword}`
  48. genHeaders.push(
  49. ` "Authorization": "Basic ${window.btoa(
  50. unescape(encodeURIComponent(basic))
  51. )}",\n`
  52. )
  53. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  54. genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
  55. }
  56. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  57. requestString.push(`${requestBody},`)
  58. }
  59. if (genHeaders.length > 0) {
  60. requestString.push(
  61. `{ \n headers : {${genHeaders.join("").slice(0, -1)}\n }\n}`
  62. )
  63. }
  64. requestString.push(").then(response => {\n")
  65. requestString.push(" console.log(response);\n")
  66. requestString.push("})")
  67. requestString.push(".catch(e => {\n")
  68. requestString.push(" console.error(e);\n")
  69. requestString.push("})\n")
  70. return requestString.join("")
  71. },
  72. }