~singpolyma/whiplash-mboa

4eb5464a843ece68f01973107e62791e80cd6d23 — Stephen Paul Weber 1 year, 6 months ago f20431d
Create new whiplash item when asked for a sku that does not exist
M app/controllers/fulfillment_controller.rb => app/controllers/fulfillment_controller.rb +3 -1
@@ 23,7 23,9 @@ class FulfillmentController < ApplicationController
				"items/sku/#{params[:sku]}",
				nil,
				"X-API-KEY" => @shop.whiplash_api_key
			).body.each_with_object({}) { |item, h| h[params[:sku]] = item["id"] }
			).body.each_with_object({}) { |item, h| h[params[:sku]] = item["id"] }.tap do |ids|
				CreateWhiplashItemJob.perform_later(@shop, params[:sku]) if ids.empty?
			end
		else
			Rails.cache.fetch("all_whiplash_items-#{@shop.id}", expires_in: 4.hours) do
				fetch_all_items.each_with_object({}) { |item, h| h[item["sku"]] = item["id"] }

A app/jobs/create_whiplash_item_job.rb => app/jobs/create_whiplash_item_job.rb +49 -0
@@ 0,0 1,49 @@
# frozen_string_literal: true

class CreateWhiplashItemJob < ApplicationJob
	queue_as :default

	def perform(shop, sku)
		shop.with_shopify_session do
			response = ShopifyAPI::Clients::Graphql::Admin.new(
				session: ShopifyAPI::Context.active_session
			).query(query: <<~GRAPHQL, variables: { q: "sku:#{sku}" })
				query fetch($q: String) {
					productVariants(first: 1, query: $q) {
						edges {
							node {
								sku
								legacyResourceId
								displayName
								price
								image {
									url
								}
							}
						}
					}
				}
			GRAPHQL

			variant = response.body&.dig("data", "productVariants", "edges", 0, "node")
			return if !variant || variant["sku"] != sku

			response = WHIPLASH_HTTP.post(
				"items",
				{
					sku: variant["sku"],
					originator_id: variant["legacyResourceId"],
					title: variant["displayName"],
					price: variant["price"],
					image_originator_url: variant.dig("image", "url")
				},
				"X-API-KEY" => shop.whiplash_api_key
			)

			Rails.logger.error response.to_s if response.status != 201
		rescue StandardError
			Sentry.capture_exception($!)
			Rails.logger.error $!.to_s
		end
	end
end

A test/jobs/create_whiplash_item_job_test.rb => test/jobs/create_whiplash_item_job_test.rb +9 -0
@@ 0,0 1,9 @@
# frozen_string_literal: true

require "test_helper"

class CreateWhiplashItemJobTest < ActiveJob::TestCase
	# test "the truth" do
	#	 assert true
	# end
end