2019-06-13 20:17:15 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module ProtocolImporters
|
|
|
|
class SearchProtocolsService
|
|
|
|
extend Service
|
2019-06-27 16:11:36 +08:00
|
|
|
require 'protocol_importers/protocols_io/v3/errors'
|
2019-06-13 20:17:15 +08:00
|
|
|
|
|
|
|
attr_reader :errors, :protocols_list
|
|
|
|
|
|
|
|
CONSTANTS = Constants::PROTOCOLS_IO_V3_API
|
|
|
|
|
|
|
|
def initialize(protocol_source:, query_params: {})
|
|
|
|
@protocol_source = protocol_source
|
2019-06-28 08:26:31 +08:00
|
|
|
@query_params = query_params.except(:protocol_source)
|
2019-06-13 20:17:15 +08:00
|
|
|
@errors = Hash.new { |h, k| h[k] = {} }
|
|
|
|
end
|
|
|
|
|
|
|
|
def call
|
|
|
|
return self unless valid?
|
|
|
|
|
2019-06-18 20:01:57 +08:00
|
|
|
# Call api client
|
2019-06-27 16:11:36 +08:00
|
|
|
api_response = api_client.protocol_list(@query_params)
|
2019-06-13 20:17:15 +08:00
|
|
|
|
2019-06-18 20:01:57 +08:00
|
|
|
# Normalize protocols list
|
2019-06-27 16:11:36 +08:00
|
|
|
@protocols_list = normalizer.normalize_list(api_response)
|
2019-06-13 20:17:15 +08:00
|
|
|
|
2019-06-27 16:11:36 +08:00
|
|
|
self
|
2019-07-03 15:34:15 +08:00
|
|
|
rescue client_errors => e
|
2019-06-27 16:11:36 +08:00
|
|
|
@errors[e.error_type] = e.message
|
|
|
|
self
|
2019-06-13 20:17:15 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def succeed?
|
|
|
|
@errors.none?
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def valid?
|
|
|
|
# try if key is not empty
|
|
|
|
@errors[:invalid_params][:key] = 'Key cannot be empty' if @query_params[:key].blank?
|
|
|
|
|
|
|
|
# try if page id is ok
|
2019-07-04 21:35:18 +08:00
|
|
|
@errors[:invalid_params][:page_id] = 'Page needs to be positive' if @query_params[:page_id]&.to_i&.negative?
|
2019-06-13 20:17:15 +08:00
|
|
|
|
|
|
|
# try if endpints exists
|
|
|
|
@errors[:invalid_params][:source_endpoint] = 'Wrong source endpoint' unless endpoint_name&.is_a?(String)
|
|
|
|
|
|
|
|
succeed?
|
|
|
|
end
|
|
|
|
|
|
|
|
def endpoint_name
|
|
|
|
Constants::PROTOCOLS_ENDPOINTS.dig(*@protocol_source.split('/').map(&:to_sym))
|
|
|
|
end
|
|
|
|
|
|
|
|
def api_client
|
|
|
|
"ProtocolImporters::#{endpoint_name}::ApiClient".constantize.new
|
|
|
|
end
|
|
|
|
|
|
|
|
def normalizer
|
|
|
|
"ProtocolImporters::#{endpoint_name}::ProtocolNormalizer".constantize.new
|
|
|
|
end
|
2019-06-18 20:01:57 +08:00
|
|
|
|
2019-07-03 15:34:15 +08:00
|
|
|
def client_errors
|
2019-06-27 20:54:19 +08:00
|
|
|
"ProtocolImporters::#{endpoint_name}::Error".constantize
|
2019-06-18 20:01:57 +08:00
|
|
|
end
|
2019-06-13 20:17:15 +08:00
|
|
|
end
|
|
|
|
end
|