PERF: Fix N+1 queries due to the loading of post custom fields. (#18)

PERF: Fix N+1 queries due to the loading of post custom fields. (#18)

diff --git a/plugin.rb b/plugin.rb
index eef97a2..5948fbd 100644
--- a/plugin.rb
+++ b/plugin.rb
@@ -48,8 +48,18 @@ after_initialize do
 
   register_post_custom_field_type(DiscourseSharedEdits::SHARED_EDITS_ENABLED, :boolean)
 
+  topic_view_post_custom_fields_allowlister { [DiscourseSharedEdits::SHARED_EDITS_ENABLED] }
+
   add_to_serializer(:post, :shared_edits_enabled) do
-    SiteSetting.shared_edits_enabled &&
-      object.custom_fields[DiscourseSharedEdits::SHARED_EDITS_ENABLED]
+    SiteSetting.shared_edits_enabled && begin
+      if @topic_view.present?
+        @topic_view.post_custom_fields.dig(
+          object.id,
+          DiscourseSharedEdits::SHARED_EDITS_ENABLED
+        )
+      else
+        object.custom_fields[DiscourseSharedEdits::SHARED_EDITS_ENABLED]
+      end
+    end
   end
 end
diff --git a/spec/serializers/post_serializer_spec.rb b/spec/serializers/post_serializer_spec.rb
new file mode 100644
index 0000000..4575b62
--- /dev/null
+++ b/spec/serializers/post_serializer_spec.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+describe PostSerializer do
+  fab!(:post) { Fabricate(:post) }
+
+  before do
+    SiteSetting.shared_edits_enabled
+  end
+
+  describe '#shared_edits_enabled' do
+    before do
+      post.custom_fields[DiscourseSharedEdits::SHARED_EDITS_ENABLED] = true
+      post.save_custom_fields
+    end
+
+    it 'should return the right value when shared edits exists for a post' do
+      payload = PostSerializer.new(post, scope: Guardian.new, root: false).as_json
+
+      expect(payload[:shared_edits_enabled]).to eq(true)
+    end
+
+    it 'should return the right value when shared edits exists in the topic view context' do
+      serializer = PostSerializer.new(post, scope: Guardian.new, root: false)
+      serializer.topic_view = TopicView.new(post.topic)
+
+      expect(serializer.as_json[:shared_edits_enabled]).to eq(true)
+    end
+  end
+end
diff --git a/spec/serializers/topic_view_serializer_spec.rb b/spec/serializers/topic_view_serializer_spec.rb
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/spec/serializers/topic_view_serializer_spec.rb

GitHub sha: bffbb048

This commit appears in #18 which was approved by SamSaffron. It was merged by tgxworld.