Class: SBF::Client::SearchEndpoint

Inherits:
EntityEndpoint show all
Defined in:
lib/stbaldricks/endpoints/search.rb

Instance Attribute Summary

Attributes inherited from EntityEndpoint

#orig_target_class

Instance Method Summary collapse

Methods inherited from EntityEndpoint

#aggregate, #create, #delete, #find_first, #get, #initialize, #save, #update

Constructor Details

This class inherits a constructor from SBF::Client::EntityEndpoint

Instance Method Details

#find(model_type, search_text = nil, filters = [], geo_location = {}, options = {}) ⇒ Client::Api::Response

Find entities in search matching the provided search term and/or filters.

Options Hash (options):

  • :order (Hash)

    The ordering to apply to the results. The hash should contain the field_name to order on as well as the direction. (i.e.) ‘foo’, direction: ‘asc’



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/stbaldricks/endpoints/search.rb', line 21

def find(model_type, search_text = nil, filters = [], geo_location = {}, options = {})
  if [search_text, filters, geo_location].all?(&:empty?)
    raise SBF::Client::Error, 'Must provide either a search_text, filter or geo_location for the query'
  end

  model_type = Array(model_type).to_json unless model_type.empty?
  filters = filters.to_json unless filters.empty?
  geo_location = geo_location.to_json unless geo_location.empty?

  # Build the parameter list for search
  params = {}
  response_data = {}
  {model_type: model_type, search_text: search_text, filters: filters, geo_location: geo_location}.each do |k, v|
    params[k.to_sym] = v unless v.empty?
  end

  options.each do |k, v|
    params[k.to_sym] = v.is_a?(Hash) ? v.to_json : v unless v.empty?
  end

  response = SBF::Client::Api::Request.get_request("#{base_uri}/search", params)
  parsed_response_body = JSON.parse(response.body).symbolize!

  if ok?(response)
    response_data[:total_count] = parsed_response_body[:total]
    response_data[:results] = [].tap do |arr|
      parsed_response_body[:hits].each do |entity_data|
        arr << target_class.const_get(entity_data[:type].capitalize).new(entity_data[:source])
      end
    end

    data = response_data
  else
    data = nil
    error = SBF::Client::ErrorEntity.new(parsed_response_body)
  end

  SBF::Client::Api::Response.new(http_code: response.code, data: data, error: error)
end