diff --git a/app/services/biomolecule_toolkit_client.rb b/app/services/biomolecule_toolkit_client.rb new file mode 100644 index 000000000..c01f1cdc4 --- /dev/null +++ b/app/services/biomolecule_toolkit_client.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +class BiomoleculeToolkitClient + MACROMOLECULES_PATH = '/api/macromolecules' + + class BiomoleculeToolkitClientException < StandardError; end + + def initialize + @host = Rails.configuration.x.biomolecule_toolkit_host + @http = Net::HTTP.new( + Rails.configuration.x.biomolecule_toolkit_host, + Rails.application.config.x.biomolecule_toolkit_port + ) + end + + def healthy? + request = Net::HTTP::Get.new('/api/health') + process_request(request)&.dig('status') == 'UP' + end + + def list + request = Net::HTTP::Get.new(MACROMOLECULES_PATH) + process_request(request) + end + + def create(params:) + request = Net::HTTP::Post.new(MACROMOLECULES_PATH, 'Content-Type': 'application/json') + request.body = params + process_request(request) + end + + def get(cid:) + request = Net::HTTP::Get.new("#{MACROMOLECULES_PATH}/#{CGI.escape(cid)}") + process_request(request) + end + + def update(cid:, params:) + request = Net::HTTP::Put.new("#{MACROMOLECULES_PATH}/#{CGI.escape(cid)}", 'Content-Type': 'application/json') + request.body = params + process_request(request) + end + + def delete + request = Net::HTTP::Delete.new("#{MACROMOLECULES_PATH}/#{CGI.escape(cid)}") + process_request(request) + end + + private + + def process_request(request) + responce = @http.request(request) + + if responce.is_a? Net::HTTPOK + JSON.parse(responce.body) + elsif responce.is_a? Net::HTTPNoContent + true + else + error_message = JSON.parse(responce.body).dig('error', 'message') + error_message ||= I18n.t('biomolecule_toolkit_client.generic_error') + raise BiomoleculeToolkitClientException, error_message + end + rescue JSON::ParserError + raise BiomoleculeToolkitClientException, I18n.t('biomolecule_toolkit_client.responce_parsing_error') + rescue StandardError + raise BiomoleculeToolkitClientException, I18n.t('biomolecule_toolkit_client.generic_error') + end +end diff --git a/config/initializers/biomolecule_toolkit_client.rb b/config/initializers/biomolecule_toolkit_client.rb new file mode 100644 index 000000000..241d21088 --- /dev/null +++ b/config/initializers/biomolecule_toolkit_client.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +Rails.application.config.x.biomolecule_toolkit_host = ENV['BIOMOLECULE_TOOLKIT_HOST'] +Rails.application.config.x.biomolecule_toolkit_port = ENV['BIOMOLECULE_TOOLKIT_PORT'] || 80 diff --git a/config/locales/biomolecule_toolkit_client/en.yml b/config/locales/biomolecule_toolkit_client/en.yml new file mode 100644 index 000000000..6739dff13 --- /dev/null +++ b/config/locales/biomolecule_toolkit_client/en.yml @@ -0,0 +1,4 @@ +en: + biomolecule_toolkit_client: + generic_error: 'Failed to execute API command' + responce_parsing_error: 'Failed to parse API response'