Class: MeiliSearch::Rails::SafeIndex

Inherits:
Object
  • Object
show all
Defined in:
lib/meilisearch-rails.rb

Overview

this class wraps an MeiliSearch::Index document ensuring all raised exceptions are correctly logged or thrown depending on the ‘raise_on_failure` option

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(index_uid, raise_on_failure, options) ⇒ SafeIndex

Returns a new instance of SafeIndex.



276
277
278
279
280
281
282
283
284
285
286
# File 'lib/meilisearch-rails.rb', line 276

def initialize(index_uid, raise_on_failure, options)
  client = MeiliSearch::Rails.client
  primary_key = options[:primary_key] || MeiliSearch::Rails::IndexSettings::DEFAULT_PRIMARY_KEY
  @raise_on_failure = raise_on_failure.nil? || raise_on_failure

  SafeIndex.log_or_throw(nil, @raise_on_failure) do
    client.create_index(index_uid, { primary_key: primary_key })
  end

  @index = client.index(index_uid)
end

Class Method Details

.log_or_throw(method, raise_on_failure, &block) ⇒ Object



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/meilisearch-rails.rb', line 333

def self.log_or_throw(method, raise_on_failure, &block)
  yield
rescue ::MeiliSearch::TimeoutError, ::MeiliSearch::ApiError => e
  raise e if raise_on_failure

  # log the error
  MeiliSearch::Rails.logger.info("[meilisearch-rails] #{e.message}")
  # return something
  case method.to_s
  when 'search'
    # some attributes are required
    { 'hits' => [], 'hitsPerPage' => 0, 'page' => 0, 'facetDistribution' => {}, 'error' => e }
  else
    # empty answer
    { 'error' => e }
  end
end

Instance Method Details

#facet_search(*args, **opts) ⇒ Object

Maually define facet_search due to complications with **opts in ruby 2.*



305
306
307
308
309
310
311
# File 'lib/meilisearch-rails.rb', line 305

def facet_search(*args, **opts)
  SafeIndex.log_or_throw(:facet_search, @raise_on_failure) do
    return MeiliSearch::Rails.black_hole unless MeiliSearch::Rails.active?

    @index.facet_search(*args, **opts)
  end
end

#settings(*args) ⇒ Object

special handling of settings to avoid raising errors on 404



323
324
325
326
327
328
329
330
331
# File 'lib/meilisearch-rails.rb', line 323

def settings(*args)
  SafeIndex.log_or_throw(:settings, @raise_on_failure) do
    @index.settings(*args)
  rescue ::MeiliSearch::ApiError => e
    return {} if e.code == 'index_not_found' # not fatal

    raise e
  end
end

#wait_for_task(task_uid) ⇒ Object

special handling of wait_for_task to handle null task_id



314
315
316
317
318
319
320
# File 'lib/meilisearch-rails.rb', line 314

def wait_for_task(task_uid)
  return if task_uid.nil? && !@raise_on_failure # ok

  SafeIndex.log_or_throw(:wait_for_task, @raise_on_failure) do
    @index.wait_for_task(task_uid)
  end
end