Skip to content

Commit

Permalink
paginate search results
Browse files Browse the repository at this point in the history
  • Loading branch information
kleinjm committed Sep 19, 2019
1 parent 737e159 commit 7eaab38
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 12 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
instacart_api (0.1.0)
instacart_api (0.1.6)

GEM
remote: https://rubygems.org/
Expand Down
3 changes: 2 additions & 1 deletion example_usage.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
)

bananas = client.search(term: "banana")
# => Array of searh result Items

# sorting will compare items by price
client.add_item_to_cart(item_id: bananas.sort.first.id, quantity: 1)
# client.add_item_to_cart(item_id: bananas.sort.first.id, quantity: 1)
36 changes: 27 additions & 9 deletions lib/instacart_api/actions/search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,43 @@
module InstacartApi
module Search
def search(term:, store: default_store)
term_query = URI.encode(term)
response = get(url: "v3/containers/#{store}/search_v3/#{term_query}?per=40")
@term_query = URI.encode(term)
@store = store
@items = []
@page = 1

parse_search_response(response: response.body)
data_json = fetch_items
total_pages = data_json.dig("pagination", "total_pages")

while @page < total_pages
@page += 1
fetch_items
end

@items
end

private

def parse_search_response(response:)
items_json(response: response).map do |item_json|
Item.new(item_json)
def fetch_items
response = get(
url: "v3/containers/#{@store}/search_v3/#{@term_query}" \
"?per=40&page=#{@page}"
)

data_json = data_json(response: response)
data_json.fetch("items").map do |item_json|
@items << Item.new(item_json)
end

data_json
end

def items_json(response:)
json_body = JSON.parse(response)
def data_json(response:)
json_body = JSON.parse(response.body)
json_body.dig("container", "modules").find do |mod|
mod["id"] =~ /search_result_set_/
end.dig("data", "items")
end.fetch("data")
end
end
end
2 changes: 1 addition & 1 deletion lib/instacart_api/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module InstacartApi
VERSION = "0.1.5"
VERSION = "0.1.6"
end

0 comments on commit 7eaab38

Please sign in to comment.