ruby-net-http.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. export const RubyNetHttpCodeGen = {
  2. id: "ruby-net-http",
  3. name: "Ruby Net::HTTP",
  4. language: "ruby",
  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. headers,
  18. }) => {
  19. const requestString = []
  20. requestString.push(`require 'net/http'\n`)
  21. // initial request setup
  22. let requestBody = rawInput ? rawParams : rawRequestBody
  23. if (requestBody) {
  24. requestBody = requestBody.replaceAll(/'/g, "\\'") // escape single-quotes for single-quoted string compatibility
  25. }
  26. const verbs = [
  27. { verb: "GET", rbMethod: "Get" },
  28. { verb: "POST", rbMethod: "Post" },
  29. { verb: "PUT", rbMethod: "Put" },
  30. { verb: "PATCH", rbMethod: "Patch" },
  31. { verb: "DELETE", rbMethod: "Delete" },
  32. ]
  33. // create URI and request
  34. const verb = verbs.find((v) => v.verb === method)
  35. if (!verb) return ""
  36. requestString.push(`uri = URI.parse('${url}${pathName}?${queryString}')\n`)
  37. requestString.push(`request = Net::HTTP::${verb.rbMethod}.new(uri)`)
  38. // custom headers
  39. if (headers) {
  40. headers.forEach(({ key, value }) => {
  41. if (key) {
  42. requestString.push(`request['${key}'] = '${value}'`)
  43. }
  44. })
  45. }
  46. // authentication
  47. if (auth === "Basic Auth") {
  48. requestString.push(`request.basic_auth('${httpUser}', '${httpPassword}')`)
  49. } else if (auth === "Bearer Token" || auth === "OAuth 2.0") {
  50. requestString.push(`request['Authorization'] = 'Bearer ${bearerToken}'`)
  51. }
  52. // set body
  53. if (["POST", "PUT", "PATCH", "DELETE"].includes(method) && requestBody) {
  54. requestString.push(`request.body = '${requestBody}'\n`)
  55. }
  56. // process
  57. requestString.push(`http = Net::HTTP.new(uri.host, uri.port)`)
  58. requestString.push(`http.use_ssl = uri.is_a?(URI::HTTPS)`)
  59. requestString.push(`response = http.request(request)\n`)
  60. // analyse result
  61. requestString.push(`unless response.is_a?(Net::HTTPSuccess) then`)
  62. requestString.push(
  63. ` raise "An error occurred: #{response.code} #{response.message}"`
  64. )
  65. requestString.push(`else`)
  66. requestString.push(` puts response.body`)
  67. requestString.push(`end`)
  68. return requestString.join("\n")
  69. },
  70. }