From 5a449246b1139914e8c7795b6038ea2e5aa2dc6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Victor=20Geonizeli?= Date: Mon, 28 Feb 2022 14:06:45 -0300 Subject: [PATCH] fix search by terms --- app/services/posts_query_resolver_service.rb | 23 ++++++++++++------ .../posts_query_resolver_serivce_spec.rb | 24 +++++++++++++++++++ 2 files changed, 40 insertions(+), 7 deletions(-) diff --git a/app/services/posts_query_resolver_service.rb b/app/services/posts_query_resolver_service.rb index afe86eb..136280c 100644 --- a/app/services/posts_query_resolver_service.rb +++ b/app/services/posts_query_resolver_service.rb @@ -13,14 +13,23 @@ class PostsQueryResolverService def call scope = Post.all - if filter[:scope] == 'follows' && current_user - scope = scope.by_user_follows(current_user) - end - - if filter[:terms] - scope = scope.by_terms(filter[:terms]) - end + scope = scope.by_user_follows(current_user) if filter[:scope] == 'follows' && current_user + scope = filter_by_terms(scope) if filter[:terms] scope end + + private + + def filter_by_terms(scope) + result = scope.by_terms(filter[:terms]) + + posts_with_quotes = result.where.not(quoted_post_id: nil) + posts_without_quotes = result.where(quoted_post_id: nil) + + quotes_ids = posts_with_quotes.pluck(:quoted_post_id) + quoted_posts = Post.where(id: quotes_ids).by_terms(filter[:terms]) + + posts_without_quotes.or(quoted_posts).order(created_at: :desc) + end end \ No newline at end of file diff --git a/spec/services/posts_query_resolver_serivce_spec.rb b/spec/services/posts_query_resolver_serivce_spec.rb index 8c6b2e9..cd783f9 100644 --- a/spec/services/posts_query_resolver_serivce_spec.rb +++ b/spec/services/posts_query_resolver_serivce_spec.rb @@ -33,5 +33,29 @@ RSpec.describe PostsQueryResolverService, type: :service do ).to eq([post1, post2]) end end + + context 'when filtering by terms' do + it 'returns only posts with terms' do + followed_user = create(:user) + create(:user_follow, follower_id: current_user.id, followed_id: followed_user.id) + + post1 = create(:post, user_id: followed_user.id, content: 'um') + post2 = create(:post, user_id: followed_user.id, content: 'dois') + post3 = create(:post, content: 'tres', quoted_post_id: post2.id) + post4 = create(:post, content: 'dois', quoted_post_id: post2.id) + + expect( + described_class.call({ terms: 'um' }, current_user) + ).to eq([post1]) + + expect( + described_class.call({ terms: 'dois' }, current_user) + ).to eq([post2]) + + expect( + described_class.call({ terms: 'tres' }, current_user) + ).to eq([]) + end + end end end \ No newline at end of file