ruby-net-http.js 2.3 KB

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