Skip to content

Instantly share code, notes, and snippets.

@jiren
Created October 20, 2013 19:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiren/7073782 to your computer and use it in GitHub Desktop.
Save jiren/7073782 to your computer and use it in GitHub Desktop.
Insearch private search and doc save api
require 'rubygems'
require 'bundler/setup'
require 'faraday'
require 'json'
# Insearch api_key got from the insearch site
ENV['INSEARCH_API_KEY'] = 'qlGXLSBnXz5LuS2KKaMXfJh2EKlxZKhP'
require File.expand_path("../insearch_client", __FILE__)
doc = {
'doc' => {
'id' => Time.now.to_i,
'type' => 'product',
'data' => {
'name' => "product #{rand(2000)}",
'offer' => "Offer #{rand(50)}",
'price' => rand(5000)
}
}
}
puts InsearchClient.save(doc) # Add doc to insearch
puts InsearchClient.search('product', type: 'product') # Args 1: query, Args 2: doc type, page: 0, per_page: 10
source 'https://rubygems.org'
gem 'faraday'
gem 'json'
class InsearchClient
DEFAULTS = { version: 'v1'}
class << self
def save(data)
post('doc', data)
end
def search(query, opts = {})
get('search', {q: query}.merge(opts))
end
def api_host
@api_host ||= (ENV['INSEARCH_API_HOST'] || 'http://insearch.r13.railsrumble.com')
end
def api_key
ENV['INSEARCH_API_KEY']
end
def connection
@conn ||= Faraday.new(url: self.api_host) do |faraday|
faraday.adapter Faraday.default_adapter
end
end
def parse_response(response)
data = JSON.parse(response.body)
case response.status
when 200
{status: 200, doc: data }
when 406
{status: 406, message: data}
when 500
{:status => 500, :message => 'invalid request'}
end
end
def get(resource, opts)
response = self.connection.get do |req|
req.url build_path(resource)
req.headers['Content-Type'] = 'application/json'
req.headers['X-Api-Key'] = InsearchClient.api_key
req.body = opts.to_json
end
parse_response(response)
end
def build_path(resource)
"/#{DEFAULTS[:version]}/#{resource}"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment