Skip to content

Commit

Permalink
Show errors in coffee bag scraping
Browse files Browse the repository at this point in the history
  • Loading branch information
miharekar committed Dec 8, 2024
1 parent e0adb94 commit ca128df
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 18 deletions.
5 changes: 3 additions & 2 deletions app/controllers/coffee_bags_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,11 @@ def scrape_info
Rails.logger.info "Scraping coffee bag info for #{params[:url]} by #{Current.user.id}"
info = CoffeeBagScraper.new.get_info(params[:url])

if info
if info && info[:error].blank?
render json: info
else
render json: {error: "Could not extract information from URL"}, status: :unprocessable_entity
error = info[:error].presence || "Could not extract information from URL"
render json: {error:}, status: :unprocessable_entity
end
end

Expand Down
26 changes: 21 additions & 5 deletions app/javascript/controllers/coffee_bag_scraper_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["url", "loader"]

async fetch() {
async fetch(event) {
if (event.type === "click") {
event.preventDefault()
}

const url = this.urlTarget.value
if (!url) return

Expand All @@ -24,12 +28,23 @@ export default class extends Controller {
body: JSON.stringify({ url })
})

if (!response.ok) throw new Error('Failed to fetch coffee info')

const data = await response.json()

if (!response.ok) {
throw new Error(data.error || 'Failed to fetch coffee info')
}

this.populateFields(data)
} catch (error) {
console.error('Error fetching coffee info:', error)
const template = document.getElementById("scraper-error-template")
const notificationHtml = template.innerHTML
const updatedNotification = notificationHtml.replace(
'Something went wrong',
error.message
)

const notificationsContainer = document.getElementById("notifications-container")
notificationsContainer.insertAdjacentHTML("beforeend", updatedNotification)
} finally {
this.loaderTarget.classList.add("hidden")

Expand All @@ -42,7 +57,8 @@ export default class extends Controller {

populateFields(data) {
const fields = [
'name', 'roast_level', 'country', 'region', 'farm', 'farmer', 'variety', 'elevation', 'processing', 'harvest_time', 'quality_score', 'tasting_notes'
'name', 'roast_level', 'country', 'region', 'farm', 'farmer', 'variety',
'elevation', 'processing', 'harvest_time', 'quality_score', 'tasting_notes'
]

fields.forEach(field => {
Expand Down
10 changes: 8 additions & 2 deletions app/javascript/controllers/notification_controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ export default class extends Controller {
static values = { timeout: { type: Number, default: 10000 } }

connect() {
enter(this.element)
this.timeout = setTimeout(() => this.hideNotification(), this.timeoutValue)
if (!this.parentHidden()) {
enter(this.element)
this.timeout = setTimeout(() => this.hideNotification(), this.timeoutValue)
}
}

close(event) {
Expand All @@ -21,4 +23,8 @@ export default class extends Controller {
this.element.remove()
})
}

parentHidden() {
return this.element.parentElement.classList.contains('hidden')
}
}
2 changes: 1 addition & 1 deletion app/lib/coffee_bag_scraper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ def get_info(url)
JSON.parse(response["content"][0]["text"]).compact_blank
rescue StandardError => e
Appsignal.report_error(e)
nil
{error: e.message}
end

private
Expand Down
20 changes: 12 additions & 8 deletions app/views/coffee_bags/_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
<div class="md:shadow sm:rounded-md sm:overflow-hidden">
<div class="px-4 py-5 bg-white dark:bg-neutral-800 sm:p-6">
<div class="grid grid-cols-6 gap-6">
<div class="col-span-6 sm:col-span-4">
<div class="col-span-6">
<%= f.label :url, "Web page with information", class: "standard-label" %>
<%= f.text_field :url,
class: "mt-1 standard-input w-full",
data: {
coffee_bag_scraper_target: "url",
scrape_url: scrape_info_roaster_coffee_bags_path(@roaster),
action: "change->coffee-bag-scraper#fetch"
} %>
<div class="flex-1 mt-3 text-sm text-neutral-600 dark:text-neutral-400">
<div class="flex flex-row items-center gap-2 md:flex-col lg:flex-row md:items-stretch lg:items-center">
<%= f.text_field :url, class: "mt-0 standard-input", data: {coffee_bag_scraper_target: "url",scrape_url: scrape_info_roaster_coffee_bags_path(@roaster),action: "change->coffee-bag-scraper#fetch"} %>
<button type="button" class="px-4 py-2 button-terracotta md:w-full lg:w-auto whitespace-nowrap" data-action="coffee-bag-scraper#fetch">
Get info
</button>
</div>
</div>
</div>
<div data-coffee-bag-scraper-target="loader" class="hidden col-span-6 mx-auto sm:col-span-2 sm:mt-5">
<%= inline_svg_tag "logo-loading.svg", class: "logo-loading size-12 sm:size-10 stroke-neutral-800 text-neutral-800 dark:text-neutral-300 dark:stroke-neutral-300" %>
Expand Down Expand Up @@ -116,3 +117,6 @@
</div>
<% end %>
</div>
<div id="scraper-error-template" class="hidden">
<%= render Notification.new(type: :alert, heading: "Error fetching coffee info", text: "Something went wrong", timeout: 3000) %>
</div>

0 comments on commit ca128df

Please sign in to comment.