java-unirest.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. const unirestMethod = verb.unirestMethod || "get"
  35. requestString.push(
  36. `HttpResponse<String> response = Unirest.${unirestMethod}("${url}${pathName}?${queryString}")\n`
  37. )
  38. if (auth === "Basic Auth") {
  39. const basic = `${httpUser}:${httpPassword}`
  40. requestString.push(
  41. `.header("authorization", "Basic ${window.btoa(
  42. unescape(encodeURIComponent(basic))
  43. )}") \n`
  44. )
  45. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  46. requestString.push(`.header("authorization", "Bearer ${bearerToken}") \n`)
  47. }
  48. // custom headers
  49. if (headers) {
  50. headers.forEach(({ key, value }) => {
  51. if (key) {
  52. requestString.push(`.header("${key}", "${value}")\n`)
  53. }
  54. })
  55. }
  56. // set body
  57. if (["POST", "PUT", "PATCH", "DELETE"].includes(method)) {
  58. if (contentType && requestBody) {
  59. if (contentType.includes("x-www-form-urlencoded")) {
  60. requestBody = `"${requestBody}"`
  61. } else {
  62. requestBody = JSON.stringify(requestBody)
  63. }
  64. }
  65. if (requestBody) {
  66. requestString.push(`.body(${requestBody})\n`)
  67. }
  68. }
  69. requestString.push(`.asString();\n`)
  70. return requestString.join("")
  71. },
  72. }