javascript-fetch.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const JavascriptFetchCodegen = {
  3. id: "js-fetch",
  4. name: "JavaScript Fetch",
  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. let genHeaders = []
  23. requestString.push(`fetch("${url}${pathName}?${queryString}", {\n`)
  24. requestString.push(` method: "${method}",\n`)
  25. if (auth === "Basic Auth") {
  26. const basic = `${httpUser}:${httpPassword}`
  27. genHeaders.push(
  28. ` "Authorization": "Basic ${window.btoa(
  29. unescape(encodeURIComponent(basic))
  30. )}",\n`
  31. )
  32. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  33. genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
  34. }
  35. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  36. let requestBody = rawInput ? rawParams : rawRequestBody
  37. if (contentType && requestBody) {
  38. if (isJSONContentType(contentType)) {
  39. requestBody = `JSON.stringify(${requestBody})`
  40. } else if (contentType.includes("x-www-form-urlencoded")) {
  41. requestBody = `"${requestBody}"`
  42. }
  43. }
  44. if (requestBody) {
  45. requestString.push(` body: ${requestBody},\n`)
  46. }
  47. }
  48. if (headers) {
  49. headers.forEach(({ key, value }) => {
  50. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  51. })
  52. }
  53. genHeaders = genHeaders.join("").slice(0, -2)
  54. if (genHeaders) {
  55. requestString.push(` headers: {\n${genHeaders}\n },\n`)
  56. }
  57. requestString.push(' credentials: "same-origin"\n')
  58. requestString.push("}).then(function(response) {\n")
  59. requestString.push(" return response.text()\n")
  60. requestString.push("}).catch(function(e) {\n")
  61. requestString.push(" console.error(e)\n")
  62. requestString.push("})")
  63. return requestString.join("")
  64. },
  65. }