java-unirest.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. export const JavaUnirestCodegen = {
  2. id: "java-unirest",
  3. name: "Java Unirest",
  4. language: "java",
  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. // initial request setup
  22. let requestBody = rawInput ? rawParams : rawRequestBody
  23. const verbs = [
  24. { verb: "GET", unirestMethod: "get" },
  25. { verb: "POST", unirestMethod: "post" },
  26. { verb: "PUT", unirestMethod: "put" },
  27. { verb: "PATCH", unirestMethod: "patch" },
  28. { verb: "DELETE", unirestMethod: "delete" },
  29. { verb: "HEAD", unirestMethod: "head" },
  30. { verb: "OPTIONS", unirestMethod: "options" },
  31. ]
  32. // create client and request
  33. const verb = verbs.find((v) => v.verb === method)
  34. requestString.push(
  35. `HttpResponse<String> response = Unirest.${verb.unirestMethod}("${url}${pathName}?${queryString}")\n`
  36. )
  37. if (auth === "Basic Auth") {
  38. const basic = `${httpUser}:${httpPassword}`
  39. requestString.push(
  40. `.header("authorization", "Basic ${window.btoa(
  41. unescape(encodeURIComponent(basic))
  42. )}") \n`
  43. )
  44. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  45. requestString.push(`.header("authorization", "Bearer ${bearerToken}") \n`)
  46. }
  47. // custom headers
  48. if (headers) {
  49. headers.forEach(({ key, value }) => {
  50. if (key) {
  51. requestString.push(`.header("${key}", "${value}")\n`)
  52. }
  53. })
  54. }
  55. if (contentType) {
  56. requestString.push(`.header("Content-Type", "${contentType}")\n`)
  57. }
  58. // set body
  59. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  60. if (contentType.includes("x-www-form-urlencoded")) {
  61. requestBody = `"${requestBody}"`
  62. } else {
  63. requestBody = JSON.stringify(requestBody)
  64. }
  65. requestString.push(`.body(${requestBody})`)
  66. }
  67. requestString.push(`\n.asString();\n`)
  68. return requestString.join("")
  69. },
  70. }