DEV: Allow loading topic associations on /categories (#31954)

`/categories` sometimes returns accompanying topics under certain site
settings. The `CategoryList` currently allows preloading for topic
custom fields via `preloaded_topic_custom_fields`, but not for topics
themselves.

This addition is required for
https://github.com/discourse/discourse-solved/pull/342.
This commit is contained in:
Natalie Tay
2025-03-24 17:40:15 +08:00
committed by GitHub
parent ea632d705c
commit af03873d37
4 changed files with 38 additions and 1 deletions

View File

@ -106,7 +106,10 @@ class CategoryList
)
end
@all_topics = TopicQuery.remove_muted_tags(@all_topics, @guardian.user).includes(:last_poster)
inclusions = [:last_poster]
preload = DiscoursePluginRegistry.category_list_topics_preloader_associations
inclusions.concat(preload) if preload.present?
@all_topics = TopicQuery.remove_muted_tags(@all_topics, @guardian.user).includes(inclusions)
end
def find_relevant_topics

View File

@ -91,6 +91,7 @@ class DiscoursePluginRegistry
define_filtered_register :topic_thumbnail_sizes
define_filtered_register :topic_preloader_associations
define_filtered_register :category_list_topics_preloader_associations
define_filtered_register :api_parameter_routes
define_filtered_register :api_key_scope_mappings

View File

@ -1442,6 +1442,12 @@ class Plugin::Instance
DiscoursePluginRegistry.register_topic_preloader_association(fields, self)
end
# When loading /categories with topics, preload topic associations
# using register_category_list_topics_preloader_associations(:association_name)
def register_category_list_topics_preloader_associations(fields)
DiscoursePluginRegistry.register_category_list_topics_preloader_association(fields, self)
end
private
def setting_category

View File

@ -471,4 +471,31 @@ RSpec.describe CategoryList do
end
end
end
describe "with displayable topics" do
fab!(:category) { Fabricate(:category, num_featured_topics: 2) }
fab!(:topic) { Fabricate(:topic, category: category) }
it "preloads topic associations" do
DiscoursePluginRegistry.register_category_list_topics_preloader_association(
:first_post,
Plugin::Instance.new,
)
category = Fabricate(:category_with_definition)
Fabricate(:topic, category: category)
CategoryFeaturedTopic.feature_topics
displayable_topics =
CategoryList
.new(Guardian.new(admin), include_topics: true)
.categories
.find { |x| x.id == category.id }
.displayable_topics
expect(displayable_topics.first.association(:first_post).loaded?).to eq(true)
DiscoursePluginRegistry.reset_register!(:category_list_topics_preloader_associations)
end
end
end