require 'restclient'
module RailsConnector
# This class provides a basic implementation for accessing the search using the cms api.
# It can be activated by making it the superclass of SearchRequest.
# It should be customized by subclassing.
class CmsApiSearchRequest
# Takes +query_string+ and +options+ for accessing Cms Api Search.
#
# +options+ is a hash and may include:
#
# :limit:: The maximum number of hits
# :offset:: The search offset
# :url:: The URL to the CMS API search
# :login:: The login for the CMS API search
# :api_key:: The api_key for the CMS API search
def initialize(query_string, options = {})
@query_string = query_string
@options = Configuration.cms_api_options.merge(options)
end
# Accesses Cms Api Search using #query and fetches search hits.
def fetch_hits
headers = {
:content_type => :json,
:accept => :json,
}
headers[:host] = @options[:http_host] if @options[:http_host].present?
hits = MultiJson.decode(
RestClient::Request.execute({
:method => :get,
:url => url,
:user => @options[:login],
:password => @options[:api_key],
:headers => headers,
:payload => MultiJson.encode({
:query => query,
:offset => @options[:offset],
:size => @options[:limit],
}),
})
)
result = SES::SearchResult.new(hits['total'])
hits['results'].each do |hit|
hard_coded_score = 1
result << SES::Hit.new(hit['id'], hard_coded_score, hit)
end
result
end
private
def url
"#{@options[:url]}/revisions/#{Workspace.current.revision_id}/objs/search"
end
def query
now = Time.now
q = [
{
"field" => "_obj_class",
"operator" => "equal",
"value" => "Image",
"negate" => true
},
{
"field" => "_valid_from",
"operator" => "less_than",
"value" => now.to_iso
},
{
"field" => "_valid_until",
"operator" => "less_than",
"value" => now.to_iso,
"negate" => true
}
]
@query_string.split(/[\s]+/).each do |word|
q << {
"field" => "*",
"operator" => "prefix_search",
"value" => word,
}
end
q
end
end
end