javascript-xhr.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { isJSONContentType } from "~/helpers/utils/contenttypes"
  2. export const JavascriptXhrCodegen = {
  3. id: "js-xhr",
  4. name: "JavaScript XHR",
  5. generator: ({
  6. auth,
  7. httpUser,
  8. httpPassword,
  9. method,
  10. url,
  11. pathName,
  12. queryString,
  13. bearerToken,
  14. headers,
  15. rawInput,
  16. rawParams,
  17. rawRequestBody,
  18. contentType,
  19. }) => {
  20. const requestString = []
  21. requestString.push("const xhr = new XMLHttpRequest()")
  22. const user = auth === "Basic Auth" ? `'${httpUser}'` : null
  23. const password = auth === "Basic Auth" ? `'${httpPassword}'` : null
  24. requestString.push(
  25. `xhr.open('${method}', '${url}${pathName}${queryString}', true, ${user}, ${password})`
  26. )
  27. if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  28. requestString.push(`xhr.setRequestHeader('Authorization', 'Bearer ${bearerToken}')`)
  29. }
  30. if (headers) {
  31. headers.forEach(({ key, value }) => {
  32. if (key) requestString.push(`xhr.setRequestHeader('${key}', '${value}')`)
  33. })
  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(`xhr.setRequestHeader('Content-Type', '${contentType}; charset=utf-8')`)
  43. requestString.push(`xhr.send(${requestBody})`)
  44. } else {
  45. requestString.push("xhr.send()")
  46. }
  47. return requestString.join("\n")
  48. },
  49. }