javascript-xhr.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. const user = auth === "Basic Auth" ? `'${httpUser}'` : null
  24. const password = auth === "Basic Auth" ? `'${httpPassword}'` : null
  25. requestString.push(
  26. `xhr.open('${method}', '${url}${pathName}?${queryString}', true, ${user}, ${password})`
  27. )
  28. if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  29. requestString.push(
  30. `xhr.setRequestHeader('Authorization', 'Bearer ${bearerToken}')`
  31. )
  32. }
  33. if (headers) {
  34. headers.forEach(({ key, value }) => {
  35. if (key)
  36. requestString.push(`xhr.setRequestHeader('${key}', '${value}')`)
  37. })
  38. }
  39. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  40. let requestBody = rawInput ? rawParams : rawRequestBody
  41. if (isJSONContentType(contentType)) {
  42. requestBody = `JSON.stringify(${requestBody})`
  43. } else if (contentType.includes("x-www-form-urlencoded")) {
  44. requestBody = `"${requestBody}"`
  45. }
  46. requestString.push(
  47. `xhr.setRequestHeader('Content-Type', '${contentType}; charset=utf-8')`
  48. )
  49. requestString.push(`xhr.send(${requestBody})`)
  50. } else {
  51. requestString.push("xhr.send()")
  52. }
  53. return requestString.join("\n")
  54. },
  55. }