http_client.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'uri'
  3. class GitLab
  4. class HttpClient
  5. attr_reader :api_token, :endpoint, :verify_ssl
  6. def initialize(endpoint, api_token, verify_ssl: true)
  7. raise 'api_token required' if api_token.blank?
  8. raise 'endpoint required' if endpoint.blank? || endpoint.exclude?('/graphql') || endpoint.scan(URI::DEFAULT_PARSER.make_regexp).blank?
  9. @api_token = api_token
  10. @endpoint = endpoint
  11. @verify_ssl = verify_ssl
  12. end
  13. # returns path of the subfolder of the endpoint if exists
  14. def endpoint_path
  15. path = URI.parse(endpoint).path
  16. return if path.blank?
  17. return if path == '/api/graphql'
  18. if path.start_with?('/')
  19. path = path[1..]
  20. end
  21. path.sub('api/graphql', '')
  22. end
  23. def perform(payload)
  24. response = UserAgent.post(
  25. endpoint,
  26. payload,
  27. {
  28. headers: headers,
  29. json: true,
  30. open_timeout: 6,
  31. read_timeout: 16,
  32. log: {
  33. facility: 'GitLab',
  34. },
  35. verify_ssl: verify_ssl,
  36. },
  37. )
  38. if !response.success?
  39. Rails.logger.error response.error
  40. raise __('GitLab request failed! Please have a look at the log file for details')
  41. end
  42. response.data
  43. end
  44. def perform_rest_get_request(variables)
  45. uri = URI.parse(endpoint)
  46. return if uri.blank? || variables.blank?
  47. response = UserAgent.get(
  48. "#{uri.scheme}://#{uri.host}/api/v4/projects/#{ERB::Util.url_encode(variables[:fullpath])}/issues/#{variables[:issue_id]}",
  49. {},
  50. {
  51. headers: headers,
  52. json: true,
  53. open_timeout: 6,
  54. read_timeout: 16,
  55. log: {
  56. facility: 'GitLab',
  57. },
  58. verify_ssl: verify_ssl,
  59. },
  60. )
  61. if !response.success?
  62. Rails.logger.error response.error
  63. return
  64. end
  65. JSON.parse(response.body)
  66. end
  67. private
  68. def headers
  69. {
  70. 'PRIVATE-TOKEN': @api_token
  71. }
  72. end
  73. end
  74. end