PERF: exclude vote fields in `topic-list-item` serializer for PMs. (#103)

PERF: exclude vote fields in topic-list-item serializer for PMs. (#103)

We shouldn’t add vote fields for personal messages since users can’t vote there. If we include then it’s creating an N+1 issue in the private-messages-all endpoint.

diff --git a/lib/discourse_voting/topic_extension.rb b/lib/discourse_voting/topic_extension.rb
index befed9e..4514c4c 100644
--- a/lib/discourse_voting/topic_extension.rb
+++ b/lib/discourse_voting/topic_extension.rb
@@ -9,7 +9,7 @@ module DiscourseVoting
     end
 
     def can_vote?
-      SiteSetting.voting_enabled && Category.can_vote?(category_id) && category && category.topic_id != id
+      @can_vote ||= SiteSetting.voting_enabled && regular? && Category.can_vote?(category_id) && category && category.topic_id != id
     end
 
     def vote_count
diff --git a/plugin.rb b/plugin.rb
index 4fc64c5..8603b4b 100755
--- a/plugin.rb
+++ b/plugin.rb
@@ -96,9 +96,12 @@ after_initialize do
       object.custom_fields.merge(enable_topic_voting: DiscourseVoting::CategorySetting.find_by(category_id: object.id).present?)
     end
 
-    add_to_serializer(:topic_list_item, :vote_count) { object.vote_count }
-    add_to_serializer(:topic_list_item, :can_vote) { object.can_vote? }
-    add_to_serializer(:topic_list_item, :user_voted) { object.user_voted?(scope.user) if scope.user }
+    add_to_serializer(:topic_list_item, :vote_count, false) { object.vote_count }
+    add_to_serializer(:topic_list_item, :can_vote, false) { object.can_vote? }
+    add_to_serializer(:topic_list_item, :user_voted, false) { object.user_voted?(scope.user) if scope.user }
+    add_to_serializer(:topic_list_item, :include_vote_count?) { object.can_vote? }
+    add_to_serializer(:topic_list_item, :include_can_vote?) { SiteSetting.voting_enabled && object.regular? }
+    add_to_serializer(:topic_list_item, :include_user_voted?) { object.can_vote? }
     add_to_serializer(:basic_category, :can_vote, false) { SiteSetting.voting_enabled }
     add_to_serializer(:basic_category, :include_can_vote?) { Category.can_vote?(object.id) }
 

GitHub sha: fc4d23174eba1a57ddcba93eaf4a4e75d469d4a4

This commit appears in #103 which was approved by udan11. It was merged by vinothkannans.