javascript-fetch.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 (isJSONContentType(contentType)) {
  38. requestBody = `JSON.stringify(${requestBody})`
  39. } else if (contentType.includes("x-www-form-urlencoded")) {
  40. requestBody = `"${requestBody}"`
  41. }
  42. requestString.push(` body: ${requestBody},\n`)
  43. genHeaders.push(` "Content-Type": "${contentType}; charset=utf-8",\n`)
  44. }
  45. if (headers) {
  46. headers.forEach(({ key, value }) => {
  47. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  48. })
  49. }
  50. genHeaders = genHeaders.join("").slice(0, -2)
  51. requestString.push(` headers: {\n${genHeaders}\n },\n`)
  52. requestString.push(' credentials: "same-origin"\n')
  53. requestString.push("}).then(function(response) {\n")
  54. requestString.push(" response.status\n")
  55. requestString.push(" response.statusText\n")
  56. requestString.push(" response.headers\n")
  57. requestString.push(" response.url\n\n")
  58. requestString.push(" return response.text()\n")
  59. requestString.push("}).catch(function(e) {\n")
  60. requestString.push(" console.error(e)\n")
  61. requestString.push("})")
  62. return requestString.join("")
  63. },
  64. }