Add ChampFetchExternalDataJob

This commit is contained in:
Paul Chavard 2021-02-09 12:35:23 +01:00
parent c343fd432e
commit 7eee14feef
4 changed files with 70 additions and 13 deletions

View file

@ -0,0 +1,11 @@
class ChampFetchExternalDataJob < ApplicationJob
def perform(champ)
if champ.external_id.present?
data = champ.fetch_external_data
if data.present?
champ.update!(data: data)
end
end
end
end

View file

@ -67,6 +67,8 @@ class Champ < ApplicationRecord
before_create :set_dossier_id, if: :needs_dossier_id?
before_validation :set_dossier_id, if: :needs_dossier_id?
before_save :cleanup_if_empty
after_update_commit :fetch_external_data_later
validates :type_de_champ_id, uniqueness: { scope: [:dossier_id, :row] }
@ -143,6 +145,14 @@ class Champ < ApplicationRecord
update_column(:fetch_external_data_exceptions, exceptions)
end
def fetch_external_data?
false
end
def fetch_external_data
raise NotImplemented.new(:fetch_external_data)
end
private
def needs_dossier_id?
@ -152,4 +162,22 @@ class Champ < ApplicationRecord
def set_dossier_id
self.dossier_id = parent.dossier_id
end
def cleanup_if_empty
if external_id_changed?
self.data = nil
end
end
def fetch_external_data_later
if fetch_external_data? && external_id.present? && data.nil?
ChampFetchExternalDataJob.perform_later(self)
end
end
class NotImplemented < ::StandardError
def initialize(method)
super(":#{method} not implemented")
end
end
end

View file

@ -18,20 +18,11 @@
# type_de_champ_id :integer
#
class Champs::AnnuaireEducationChamp < Champs::TextChamp
before_save :cleanup_if_empty
after_update_commit :fetch_data
private
def cleanup_if_empty
if external_id_changed?
self.data = nil
end
def fetch_external_data?
true
end
def fetch_data
if external_id.present? && data.nil?
AnnuaireEducationUpdateJob.perform_later(self)
end
def fetch_external_data
ApiEducation::AnnuaireEducationAdapter.new(external_id).to_params
end
end

View file

@ -522,4 +522,31 @@ describe Champ do
it { expect(champ.fetch_external_data_exceptions).to eq(['#<StandardError: My special exception!>']) }
end
end
describe "fetch_external_data" do
let(:champ) { create(:champ_text, data: 'some data') }
context "cleanup_if_empty" do
it "remove data if external_id changes" do
expect(champ.data).to_not be_nil
champ.update(external_id: 'external_id')
expect(champ.data).to be_nil
end
end
context "fetch_external_data_later" do
include ActiveJob::TestHelper
let(:data) { 'some other data' }
it "fill data from external source" do
expect(champ).to receive(:fetch_external_data?) { true }
expect_any_instance_of(Champs::TextChamp).to receive(:fetch_external_data) { data }
perform_enqueued_jobs do
champ.update(external_id: 'external_id')
end
expect(champ.reload.data).to eq data
end
end
end
end