Class: Dina::SearchConnection

Inherits:
Object
  • Object
show all
Defined in:
lib/dina/search/search_connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) {|_self| ... } ⇒ SearchConnection

Returns a new instance of SearchConnection.

Yields:

  • (_self)

Yield Parameters:



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/dina/search/search_connection.rb', line 6

def initialize(options = {})
  site = options.fetch(:site)
  connection_options = options.slice(:proxy, :ssl, :request, :headers, :params)
  adapter_options = Array(options.fetch(:adapter, Faraday.default_adapter))

  @faraday = Faraday.new(site, connection_options) do |builder|
    builder.request :json
    builder.response :json
    builder.adapter(*adapter_options)
  end
  yield(self) if block_given?
end

Instance Method Details

#custom_headersObject



29
30
31
# File 'lib/dina/search/search_connection.rb', line 29

def custom_headers
  { content_type: "application/json", authorization: Dina.header }
end

#index_name(index:) ⇒ String

Sets the search index name

Parameters:

  • index (String)

    the search index; options are "agent", "material_sample", "object_store"

Returns:

  • (String)

    the internally-recognized search index name



24
25
26
27
# File 'lib/dina/search/search_connection.rb', line 24

def index_name(index:)
  return nil if !index
  "dina_#{index}_index"
end

#run(request_method, path, params: nil, headers: {}, body: nil) ⇒ Object



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
60
61
62
# File 'lib/dina/search/search_connection.rb', line 33

def run(request_method, path, params: nil, headers: {}, body: nil)
  path.slice!("/execute")
  if params && params.has_key?(:index)
    params.merge!(indexName: index_name(index: params[:index]))
  elsif body && body.has_key?(:index)
    params = { indexName: index_name(index: body[:index]) }
  end
  payload = JSON.generate(body[:payload]) rescue ""

  response = @faraday.run_request(request_method, path, body, headers) do |request|
    request.params.update(params) if params
    request.headers = custom_headers
    request.body = payload
  end

  attributes = response.body.dup
  meta = {}
  if attributes.has_key?("hits")
    #TODO: does not work with SearchAutoComplete because response is different from Search
    meta["count"] = attributes["hits"]["total"]["value"] rescue 0
  elsif attributes.has_key?("count")
    meta["count"] = attributes["count"]
  elsif attributes.has_key?("attributes")
    meta = attributes
  end
  response.body["meta"] = meta
  response.body["errors"] = []
  response.body["data"] = attributes["hits"]["hits"].map{|d| d["_source"]["data"]} rescue []
  response
end

#use(middleware, *args, &block) ⇒ Object



64
65
66
# File 'lib/dina/search/search_connection.rb', line 64

def use(middleware, *args, &block)
  return if @faraday.builder.locked?
end