Skip to content

Instantly share code, notes, and snippets.

@ezefranca
Created March 13, 2023 19:25
Show Gist options
  • Save ezefranca/af458941783e7734dbd246dfe423eb1a to your computer and use it in GitHub Desktop.
Save ezefranca/af458941783e7734dbd246dfe423eb1a to your computer and use it in GitHub Desktop.
Quem trouxe, quem trouxe.
require 'net/http'
require 'json'
Encoding.default_external = 'UTF-8'
query = params['query'] || 'banana'
page = (params['page'] || 0).to_i
from = page * 100
uri = URI('https://mercadao.pt/api/catalogues/6107d28d72939a003ff6bf51/products/search')
uri.query = URI.encode_www_form({
query: query,
from: "#{from}",
size: "100",
esPreference: "0.03859005288751671",
})
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
data = JSON.parse(res.body)
search_items = data.dig("sections", query, "products")
&.map { |product| product.dig("_source") }
&.compact
&.map do |product|
title = product.dig("firstName")
price = "#{product.dig("buyingPrice")&.round(2)} €"
price_kg = product.dig("capacity") == "0" ? "un" : nil
img_url = "https://res.cloudinary.com/fonte-online/image/upload/c_fill,h_300,q_auto,w_300/v1/PDO_PROD/#{product.dig("sku")}_1"
brand = product.dig("brand", "name")
quantity = product.dig("capacity") || ""
destiny_url = product.dig("firstName") || ""
supermarket = "Mercadão"
{
title: title,
price: price,
price_kg: price_kg,
unit: "",
img_url: img_url,
brand: brand,
quantity: quantity,
destiny_url: destiny_url,
supermarket: supermarket
}
end
result = {
query: query,
page: page,
total_items: search_items&.size,
search_items: search_items,
url: uri.to_s
}
else
puts "HTTP error: #{res.code}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment