DEV: Allow additional TopicList preloaded associations (#18891)

This provides a means to allow additional associations to be preloaded when generating a TopicList.
This commit is contained in:
jbrw 2022-12-12 09:08:13 -05:00 committed by GitHub
parent 2a4fea4372
commit 1a48ea767e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 25 additions and 1 deletions

View File

@ -136,8 +136,11 @@ class TopicList
ft.topic_list = self ft.topic_list = self
end end
topic_preloader_associations = [:image_upload, { topic_thumbnails: :optimized_image }]
topic_preloader_associations.concat(DiscoursePluginRegistry.topic_preloader_associations.to_a)
ActiveRecord::Associations::Preloader ActiveRecord::Associations::Preloader
.new(records: @topics, associations: [:image_upload, topic_thumbnails: :optimized_image]) .new(records: @topics, associations: topic_preloader_associations)
.call .call
if preloaded_custom_fields.present? if preloaded_custom_fields.present?

View File

@ -80,6 +80,7 @@ class DiscoursePluginRegistry
define_filtered_register :group_params define_filtered_register :group_params
define_filtered_register :topic_thumbnail_sizes define_filtered_register :topic_thumbnail_sizes
define_filtered_register :topic_preloader_associations
define_filtered_register :api_parameter_routes define_filtered_register :api_parameter_routes
define_filtered_register :api_key_scope_mappings define_filtered_register :api_key_scope_mappings

View File

@ -1220,6 +1220,10 @@ class Plugin::Instance
end end
end end
def register_topic_preloader_associations(fields)
DiscoursePluginRegistry.register_topic_preloader_association(fields, self)
end
private private
def validate_directory_column_name(column_name) def validate_directory_column_name(column_name)

View File

@ -919,6 +919,22 @@ RSpec.describe TopicQuery do
end end
end end
context 'when preloading associations' do
it "preloads associations" do
DiscoursePluginRegistry.register_topic_preloader_association(:first_post, Plugin::Instance.new)
topic = Fabricate(:topic)
Fabricate(:post, topic: topic)
new_topic = topic_query.list_new.topics.first
expect(new_topic.association(:image_upload).loaded?).to eq(true) # Preloaded by default
expect(new_topic.association(:first_post).loaded?).to eq(true) # Testing a user-defined preloaded association
expect(new_topic.association(:user).loaded?).to eq(false) # Testing the negative
DiscoursePluginRegistry.reset_register!(:topic_preloader_associations)
end
end
context 'with a new topic' do context 'with a new topic' do
let!(:new_topic) { Fabricate(:topic, user: creator, bumped_at: 10.minutes.ago) } let!(:new_topic) { Fabricate(:topic, user: creator, bumped_at: 10.minutes.ago) }
let(:topics) { topic_query.list_new.topics } let(:topics) { topic_query.list_new.topics }