diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb
index e87fbb6..dcf6c43 100644
--- a/app/controllers/products_controller.rb
+++ b/app/controllers/products_controller.rb
@@ -1,6 +1,6 @@
class ProductsController < ApplicationController
before_action :set_product, only: %i[show edit update destroy]
- before_action :create_session, only: %i[create update destroy]
+ before_action :create_session, only: %i[create update destroy search]
def index
@products = Product.all
@@ -45,6 +45,38 @@ def destroy
redirect_to products_path, notice: 'The product was successfully destroyed.'
end
+ def search
+ url = URI.parse('https://rubylab2.myshopify.com/admin/api/2023-04/graphql.json')
+ http = Net::HTTP.new(url.host, url.port)
+ http.use_ssl = true
+
+ request = Net::HTTP::Post.new(url.path)
+ request['Content-Type'] = 'application/json'
+ request['X-Shopify-Access-Token'] = cookies[:shopify_app_session]
+ request.body = {
+ query: <<~GRAPHQL,
+ query($searchTerm: String) {
+ products(first: 10, query: $searchTerm) {
+ edges {
+ node {
+ id
+ title
+ }
+ }
+ }
+ }
+ GRAPHQL
+ variables: { searchTerm: params[:query] }
+ }.to_json
+
+ response = http.request(request)
+ result = JSON.parse(response.body)
+ @products = result.dig("data", "products", "edges").to_a
+ @our_products = @products.map do |product|
+ Product.find_by(shopify_id: product.dig("node", "id").split("/").last)
+ end
+ end
+
private
def set_product
diff --git a/app/views/products/index.html.erb b/app/views/products/index.html.erb
index e5c9e8e..13eb33d 100644
--- a/app/views/products/index.html.erb
+++ b/app/views/products/index.html.erb
@@ -1,5 +1,11 @@
-
All Products
+Search Products
+
+<%= form_tag search_path, method: :get do %>
+ <%= text_field_tag :query, params[:query], placeholder: "Enter product name" %>
+ <%= submit_tag "Search" %>
+<% end %>
+All Products
| Title |
diff --git a/app/views/products/search.html.erb b/app/views/products/search.html.erb
new file mode 100644
index 0000000..503c5b6
--- /dev/null
+++ b/app/views/products/search.html.erb
@@ -0,0 +1,19 @@
+Found Products
+<% if @our_products.empty? %>
+ Oops, looks like nothing is here.
+<% else %>
+
+
+ | Title |
+ Edit product |
+ Delete product |
+
+ <% @our_products.each do |product| %>
+
+ | <%= link_to product.title, product_path(product) %> |
+ <%= link_to 'Edit', edit_product_path(product) %> |
+ <%= button_to 'Destroy', product_path(product), method: :delete, data: { confirm: 'Are you sure?' } %> |
+
+ <% end %>
+
+<% end %>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index fee72a2..4468cb4 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -4,6 +4,7 @@
get '/auth/callback', to: 'shopify_auth#callback'
get '/import_shopify_data', to: 'shopify_import#import'
post '/webhooks/shopify/product_updated', to: 'webhooks#product_updated'
+ get '/search', to: 'products#search'
resources :orders do
member do
post :cancel