http_client.rb 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. private
  45. def headers
  46. {
  47. 'PRIVATE-TOKEN': @api_token
  48. }
  49. end
  50. end
  51. end