review: query the db only once

This commit is contained in:
sebastiencarceles 2022-12-01 11:17:48 +01:00
parent ab30af5fe5
commit 1e21a3d3e1
6 changed files with 86 additions and 42 deletions

View file

@ -1229,10 +1229,10 @@ class Dossier < ApplicationRecord
cloned_dossier
end
def find_champ_by_stable_id(stable_id)
return nil if stable_id.blank?
def find_champs_by_stable_ids(stable_ids)
return [] if stable_ids.compact.empty?
champs_public.joins(:type_de_champ).find_by(types_de_champ: { stable_id: stable_id })
champs_public.joins(:type_de_champ).where(types_de_champ: { stable_id: stable_ids })
end
private

View file

@ -5,15 +5,47 @@ class PrefillParams
end
def to_a
@params
.to_unsafe_hash
.map { |key, value| PrefillValue.new(@dossier, key, value) }
# Builds: [{ stable_id: 1, value: "a value" }, { stable_id: 2, value: "another value"}]
stable_ids_and_values = convert_typed_ids_to_stable_ids
# Builds: [{stable_id: "1", champ: #<Champs::...>}, {stable_id: "2", champ: #<Champs::...>}]
stable_ids_and_champs = find_champs(stable_ids_and_values.map { _1[:stable_id] })
# Merges the arrays together, filters out the values we don't want and returns [{ id: champ_1_id, value: value_1}, ...]
merge_by_stable_ids(stable_ids_and_values + stable_ids_and_champs)
.map { PrefillValue.new(champ: _1[:champ], value: _1[:value]) }
.filter(&:prefillable?)
.map(&:to_h)
end
private
def convert_typed_ids_to_stable_ids
@params
.to_unsafe_hash
.map { |typed_id, value| { stable_id: stable_id_from_typed_id(typed_id), value: value } }
.filter { _1[:stable_id].present? && _1[:value].present? }
end
def find_champs(stable_ids)
@dossier
.find_champs_by_stable_ids(stable_ids)
.map { |champ| { stable_id: champ.stable_id.to_s, champ: champ } }
end
def merge_by_stable_ids(arrays_of_hashes_with_stable_id)
arrays_of_hashes_with_stable_id
.group_by { _1[:stable_id] }
.values
.map { _1.reduce(:merge) }
end
def stable_id_from_typed_id(typed_id)
Champ.id_from_typed_id(typed_id)
rescue
nil
end
class PrefillValue
AUTHORIZED_TYPES_DE_CHAMPS = [
TypeDeChamp.type_champs.fetch(:text),
@ -39,8 +71,8 @@ class PrefillParams
attr_reader :champ, :value
def initialize(dossier, typed_id, value)
@champ = find_champ(dossier, typed_id)
def initialize(champ:, value:)
@champ = champ
@value = value
end
@ -71,12 +103,5 @@ class PrefillParams
champ.value = value
champ.valid?
end
def find_champ(dossier, typed_id)
stable_id = Champ.id_from_typed_id(typed_id) rescue nil
return unless stable_id
dossier.find_champ_by_stable_id(stable_id)
end
end
end