Skip to content

Instantly share code, notes, and snippets.

@kofiasare
Last active February 22, 2022 01:09
Show Gist options
  • Save kofiasare/0a97e39d404cf25be36d19f111846d01 to your computer and use it in GitHub Desktop.
Save kofiasare/0a97e39d404cf25be36d19f111846d01 to your computer and use it in GitHub Desktop.
Meilisearch: Search multiple indexes using graphql and parallel gems with Rails
module Queries
class Search < BaseQuery
include SearchHelper
type [Types::SearchResultsType], null: true
argument :query, String, required: true
argument :models, [String], required: true, default_value: ['AppUser']
def resolve(**args)
search(args)
end
end
end
module SearchHelper
SEARCH_MODELS = %w[AppUser Market Organisation]
def search(args)
raise Errors::SearchError::BlankQueryError if args[:query].blank?
raise Errors::SearchError::UnpermittedQueryError if args[:query] == '*'
models = args[:models].map { |m| m.tr(' ', '').camelize }
if models.difference(SEARCH_MODELS).any?
raise Errors::SearchError::UnknownSearchModelError
end
Parallel.flat_map(models, in_threads: models.size) do |m|
m.constantize.search(args[:query])
end
end
end
module Types
class SearchResultsType < Types::BaseUnion
description 'Models which may be searched on'
possible_types(
Types::AppUserType,
Types::MarketType,
Types::OrganisationType,
)
def self.resolve_type(object, context)
if object.is_a?(AppUser)
Types::AppUserType
elsif object.is_a?(Market)
Types::MarketType
else
Types::OrganisationType
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment