class MeiliSearch::SafeIndex

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

Public Class Methods

new(index_uid, raise_on_failure, options) click to toggle source
# File lib/meilisearch-rails.rb, line 243
def initialize(index_uid, raise_on_failure, options)
  client = MeiliSearch.client
  primary_key = options[:primary_key] ||  MeiliSearch::IndexSettings::DEFAULT_PRIMARY_KEY
  @index = client.get_or_create_index(index_uid, { primaryKey: primary_key })
  @raise_on_failure = raise_on_failure.nil? || raise_on_failure
end

Private Class Methods

log_or_throw(method, raise_on_failure) { || ... } click to toggle source
# File lib/meilisearch-rails.rb, line 284
def self.log_or_throw(method, raise_on_failure, &block)
  begin
    yield
  rescue ::MeiliSearch::ApiError => e
    raise e if raise_on_failure
    # log the error
    (Rails.logger || Logger.new(STDOUT)).error("[meilisearch-rails] #{e.message}")
    # return something
    case method.to_s
    when 'search'
      # some attributes are required
      { 'hits' => [], 'hitsPerPage' => 0, 'page' => 0, 'facetsDistribution' => {}, 'error' => e }
    else
      # empty answer
      { 'error' => e }
    end
  end
end

Public Instance Methods

settings(*args) click to toggle source

special handling of settings to avoid raising errors on 404

# File lib/meilisearch-rails.rb, line 272
def settings(*args)
  SafeIndex.log_or_throw(:settings, @raise_on_failure) do
    begin
      @index.settings(*args)
    rescue ::MeiliSearch::ApiError => e
      return {} if e.code == 404 # not fatal
      raise e
    end
  end
end
wait_for_pending_update(update_id) click to toggle source

special handling of wait_for_pending_update to handle null task_id

# File lib/meilisearch-rails.rb, line 264
def wait_for_pending_update(update_id)
  return if update_id.nil? && !@raise_on_failure # ok
  SafeIndex.log_or_throw(:wait_for_pending_update, @raise_on_failure) do
    @index.wait_for_pending_update(update_id)
  end
end