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.



257
258
259
260
261
262
263
264
265
266
267
# File 'lib/meilisearch-rails.rb', line 257

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



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/meilisearch-rails.rb', line 305

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

#settings(*args) ⇒ Object

special handling of settings to avoid raising errors on 404



295
296
297
298
299
300
301
302
303
# File 'lib/meilisearch-rails.rb', line 295

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

    raise e
  end
end

#wait_for_task(task_uid) ⇒ Object

special handling of wait_for_task to handle null task_id



286
287
288
289
290
291
292
# File 'lib/meilisearch-rails.rb', line 286

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