javascript-xhr.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const JavascriptXhrCodegen = {
  3. id: "js-xhr",
  4. name: "JavaScript XHR",
  5. language: "javascript",
  6. generator: ({
  7. auth,
  8. httpUser,
  9. httpPassword,
  10. method,
  11. url,
  12. pathName,
  13. queryString,
  14. bearerToken,
  15. headers,
  16. rawInput,
  17. rawParams,
  18. rawRequestBody,
  19. contentType,
  20. }) => {
  21. const requestString = []
  22. requestString.push("const xhr = new XMLHttpRequest()")
  23. requestString.push(`xhr.addEventListener("readystatechange", function() {`)
  24. requestString.push(` if(this.readyState === 4) {`)
  25. requestString.push(` console.log(this.responseText)\n }\n})`)
  26. const user = auth === "Basic Auth" ? `'${httpUser}'` : null
  27. const password = auth === "Basic Auth" ? `'${httpPassword}'` : null
  28. requestString.push(
  29. `xhr.open('${method}', '${url}${pathName}?${queryString}', true, ${user}, ${password})`
  30. )
  31. if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  32. requestString.push(
  33. `xhr.setRequestHeader('Authorization', 'Bearer ${bearerToken}')`
  34. )
  35. }
  36. if (headers) {
  37. headers.forEach(({ key, value }) => {
  38. if (key)
  39. requestString.push(`xhr.setRequestHeader('${key}', '${value}')`)
  40. })
  41. }
  42. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  43. let requestBody = rawInput ? rawParams : rawRequestBody
  44. if (contentType && requestBody) {
  45. if (isJSONContentType(contentType)) {
  46. requestBody = `JSON.stringify(${requestBody})`
  47. } else if (contentType.includes("x-www-form-urlencoded")) {
  48. requestBody = `"${requestBody}"`
  49. }
  50. }
  51. requestBody = requestBody || ""
  52. requestString.push(`xhr.send(${requestBody})`)
  53. } else {
  54. requestString.push("xhr.send()")
  55. }
  56. return requestString.join("\n")
  57. },
  58. }