From 54ccef47669759b060370c1cde8f527ce6d39333 Mon Sep 17 00:00:00 2001 From: rhymes Date: Sun, 31 Mar 2019 16:47:48 +0200 Subject: [PATCH] Fix error with articles API and unknown username (#2247) Currently the articles API breaks the server when called with an unknown username. It should return nothing like when called with an unknown tag. --- app/services/article_api_index_service.rb | 12 +++++++----- spec/requests/api/v0/articles_spec.rb | 6 ++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/app/services/article_api_index_service.rb b/app/services/article_api_index_service.rb index 95e6f1a82..9f7a0b736 100644 --- a/app/services/article_api_index_service.rb +++ b/app/services/article_api_index_service.rb @@ -1,8 +1,9 @@ class ArticleApiIndexService attr_accessor :tag, :username, :page, :state, :top + def initialize(params) - @page = params[:page] - @tag = params[:tag] + @page = params[:page] + @tag = params[:tag] @username = params[:username] @state = params[:state] @top = params[:top] @@ -18,8 +19,8 @@ class ArticleApiIndexService else base_articles end - articles. - decorate + + articles.decorate end private @@ -30,6 +31,7 @@ class ArticleApiIndexService else 30 end + if (user = User.find_by(username: username)) user.articles. where(published: true). @@ -45,7 +47,7 @@ class ArticleApiIndexService page(page). per(num) else - not_found + Article.none end end diff --git a/spec/requests/api/v0/articles_spec.rb b/spec/requests/api/v0/articles_spec.rb index e01b15d4f..302ba1eb5 100644 --- a/spec/requests/api/v0/articles_spec.rb +++ b/spec/requests/api/v0/articles_spec.rb @@ -26,6 +26,12 @@ RSpec.describe "Api::V0::Articles", type: :request do expect(JSON.parse(response.body).size).to eq(2) end + it "returns no articles if username param is unknown" do + create(:article, user_id: user1.id) + get "/api/articles?username=foobar" + expect(JSON.parse(response.body).size).to eq(0) + end + it "returns organization articles if username param is present" do org = create(:organization) create(:article, user_id: user1.id)