Skip to content

Commit

Permalink
Dataloading person's current roles
Browse files Browse the repository at this point in the history
  • Loading branch information
mike3985 committed Dec 19, 2024
1 parent 96561ff commit 5ec7515
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 23 deletions.
42 changes: 42 additions & 0 deletions app/graphql/sources/person_current_roles_source.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
module Sources
class PersonCurrentRolesSource < GraphQL::Dataloader::Source
def fetch(person_content_ids)
all_roles = Edition
.live
.includes(
document: {
reverse_links: { # role -> role_appointment
link_set: {
documents: [
:editions, # role_appointment
:link_set_links, # role_appointment -> person
],
},
},
},
)
.where(
document_type: "ministerial_role",
document: { locale: "en" },
reverse_links: { link_type: "role" },
editions_documents: { document_type: "role_appointment" },
link_set_links: { target_content_id: person_content_ids, link_type: "person" },
)
.where("editions_documents.details ->> 'current' = 'true'") # editions_documents is the alias that Active Record gives to the role_appointment Editions in the SQL query
.order(reverse_links: { position: :asc })

ids_map = person_content_ids.index_with { [] }

all_roles.each_with_object(ids_map) { |role, hash|
person_content_id = role.document.reverse_links
.select { |link| link.link_type == "role" } # role -> role_appointment
.flat_map { |link| link.link_set.documents }
.flat_map(&:link_set_links)
.select { |link| link.link_type == "person" } # role_appointment -> person
.map(&:target_content_id).first

hash[person_content_id] << role
}.values
end
end
end
25 changes: 2 additions & 23 deletions app/graphql/types/ministers_index_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,29 +59,8 @@ class MinistersIndexPersonLinks < Types::BaseObject
field :role_appointments, [MinistersIndexRoleAppointment]

def role_appointments
Edition
.live
.includes(
document: {
reverse_links: { # role -> role_appointment
link_set: {
documents: [
:editions, # role_appointment
:link_set_links, # role_appointment -> person
],
},
},
},
)
.where(
document_type: "ministerial_role",
document: { locale: "en" },
reverse_links: { link_type: "role" },
editions_documents: { document_type: "role_appointment" },
link_set_links: { target_content_id: object.content_id, link_type: "person" },
)
.where("editions_documents.details ->> 'current' = 'true'") # editions_documents is the alias that Active Record gives to the role_appointment Editions in the SQL query
.order(reverse_links: { position: :asc })
dataloader.with(Sources::PersonCurrentRolesSource)
.load(object.content_id)
end
end

Expand Down

0 comments on commit 5ec7515

Please sign in to comment.