javascript-jquery.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. rawRequestBody,
  17. contentType,
  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. const requestBody = rawInput ? rawParams : rawRequestBody
  27. if (requestBody.length !== 0) {
  28. requestString.push(`,\n body: ${requestBody}`)
  29. }
  30. if (headers) {
  31. headers.forEach(({ key, value }) => {
  32. if (key) genHeaders.push(` "${key}": "${value}",\n`)
  33. })
  34. }
  35. if (contentType) {
  36. genHeaders.push(` "Content-Type": "${contentType}; charset=utf-8",\n`)
  37. requestString.push(`,\n contentType: "${contentType}; charset=utf-8"`)
  38. }
  39. if (auth === "Basic Auth") {
  40. const basic = `${httpUser}:${httpPassword}`
  41. genHeaders.push(
  42. ` "Authorization": "Basic ${window.btoa(
  43. unescape(encodeURIComponent(basic))
  44. )}",\n`
  45. )
  46. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  47. genHeaders.push(` "Authorization": "Bearer ${bearerToken}",\n`)
  48. }
  49. requestString.push(
  50. `,\n headers: {\n${genHeaders.join("").slice(0, -2)}\n }\n})`
  51. )
  52. requestString.push(".then(response => {\n")
  53. requestString.push(" console.log(response);\n")
  54. requestString.push("})")
  55. requestString.push(".catch(e => {\n")
  56. requestString.push(" console.error(e);\n")
  57. requestString.push("})\n")
  58. return requestString.join("")
  59. },
  60. }