Skip to content

Commit

Permalink
Dataloading links_fields
Browse files Browse the repository at this point in the history
  • Loading branch information
mike3985 committed Dec 19, 2024
1 parent a8b1637 commit 96561ff
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
23 changes: 23 additions & 0 deletions app/graphql/sources/linked_to_editions_source.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module Sources
class LinkedToEditionsSource < GraphQL::Dataloader::Source
def initialize(parent_object:)
@object = parent_object
@content_store = parent_object.content_store.to_sym
end

def fetch(link_types)
all_links = @object.document.link_set_links
.includes(target_documents: @content_store) # content_store is :live or :draft (a Document has_one Edition by that name)
.where(link_type: link_types)
.where(target_documents: { locale: "en" })

link_types_map = link_types.index_with { [] }

all_links.each_with_object(link_types_map) { |link, hash|
hash[link.link_type].concat(
link.target_documents.map { |document| document.send(@content_store) },
)
}.values
end
end
end
11 changes: 2 additions & 9 deletions app/graphql/types/base_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,8 @@ def self.links_field(field_name_and_link_type, graphql_field_type)
field(field_name_and_link_type.to_sym, graphql_field_type)

define_method(field_name_and_link_type.to_sym) do
Edition
.live
.includes(document: { reverse_links: :link_set })
.where(
document: { locale: "en" },
link_set: { content_id: object.content_id },
reverse_links: { link_type: field_name_and_link_type.to_s },
)
.order(reverse_links: { position: :asc })
dataloader.with(Sources::LinkedToEditionsSource, parent_object: object)
.load(field_name_and_link_type.to_s)
end
end
end
Expand Down

0 comments on commit 96561ff

Please sign in to comment.