javascript-jquery.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. export const JavascriptJqueryCodegen = {
  2. id: "js-jquery",
  3. name: "JavaScript jQuery",
  4. language: "javascript",
  5. generator: ({
  6. url,
  7. pathName,
  8. queryString,
  9. auth,
  10. httpUser,
  11. httpPassword,
  12. bearerToken,
  13. method,
  14. rawInput,
  15. rawParams,
  16. contentType,
  17. rawRequestBody,
  18. headers,
  19. }) => {
  20. const requestString = []
  21. const genHeaders = []
  22. requestString.push(
  23. `jQuery.ajax({\n url: "${url}${pathName}?${queryString}"`
  24. )
  25. requestString.push(`,\n method: "${method.toUpperCase()}"`)
  26. let requestBody = rawInput ? rawParams : rawRequestBody
  27. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  28. if (contentType && contentType.includes("x-www-form-urlencoded")) {
  29. requestBody = `"${requestBody}"`
  30. } else {
  31. requestBody = requestBody.replaceAll("}", " }")
  32. }
  33. requestString.push(`,\n data: ${requestBody}`)
  34. }
  35. if (headers) {
  36. headers.forEach(({ key, value }) => {
  37. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  38. })
  39. }
  40. if (auth === "Basic Auth") {
  41. const basic = `${httpUser}:${httpPassword}`
  42. genHeaders.push(
  43. ` "Authorization": "Basic ${window.btoa(
  44. unescape(encodeURIComponent(basic))
  45. )}",\n`
  46. )
  47. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  48. genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
  49. }
  50. if (genHeaders.length > 0) {
  51. requestString.push(
  52. `,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }`
  53. )
  54. }
  55. requestString.push("\n}).then(response => {\n")
  56. requestString.push(" console.log(response);\n")
  57. requestString.push("})")
  58. requestString.push(".catch(e => {\n")
  59. requestString.push(" console.error(e);\n")
  60. requestString.push("})\n")
  61. return requestString.join("")
  62. },
  63. }