diff --git a/app/controllers/admin/dfc_product_imports_controller.rb b/app/controllers/admin/dfc_product_imports_controller.rb index ff5386f662..1b3f8dfb88 100644 --- a/app/controllers/admin/dfc_product_imports_controller.rb +++ b/app/controllers/admin/dfc_product_imports_controller.rb @@ -20,7 +20,7 @@ module Admin catalog_url = params.require(:catalog_url) - json_catalog = fetch_catalog(catalog_url) + json_catalog = DfcRequest.new(spree_current_user).get(catalog_url) graph = DfcIo.import(json_catalog) # * First step: import all products for given enterprise. @@ -34,29 +34,6 @@ module Admin private - def fetch_catalog(url) - connection = Faraday.new( - request: { timeout: 30 }, - headers: { - 'Content-Type' => 'application/json', - 'Authorization' => "Bearer #{spree_current_user.oidc_account.token}", - } - ) - response = only_public_connections do - connection.get(url) - end - - response.body - end - - def only_public_connections - return yield if Rails.env.development? - - PrivateAddressCheck.only_public_connections do - yield - end - end - # Most of this code is the same as in the DfcProvider::SuppliedProductsController. def import_product(subject, enterprise) return unless subject.is_a? DataFoodConsortium::Connector::SuppliedProduct diff --git a/engines/dfc_provider/app/services/dfc_request.rb b/engines/dfc_provider/app/services/dfc_request.rb new file mode 100644 index 0000000000..48f666b115 --- /dev/null +++ b/engines/dfc_provider/app/services/dfc_request.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +require "private_address_check" +require "private_address_check/tcpsocket_ext" + +# Request a JSON document from a DFC API with authentication. +class DfcRequest + def initialize(user) + @user = user + end + + def get(url) + connection = Faraday.new( + request: { timeout: 30 }, + headers: { + 'Content-Type' => 'application/json', + 'Authorization' => "Bearer #{@user.oidc_account.token}", + } + ) + response = only_public_connections do + connection.get(url) + end + + response.body + end + + private + + def only_public_connections(&) + return yield if Rails.env.development? + + PrivateAddressCheck.only_public_connections(&) + end +end