From c99fb27451cb52a61b602569f6024169cb3bbf19 Mon Sep 17 00:00:00 2001 From: rhymes Date: Mon, 1 Apr 2019 12:24:17 +0200 Subject: [PATCH] Add published in the SQL query to retrieve article (#2248) Since we're already asking the DB to retrieve an article, we can directly ask it to filter out published articles without checking at runtime. --- app/controllers/api/v0/articles_controller.rb | 7 ++++--- spec/requests/api/v0/articles_spec.rb | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/app/controllers/api/v0/articles_controller.rb b/app/controllers/api/v0/articles_controller.rb index cd1a7a201..2a71f6018 100644 --- a/app/controllers/api/v0/articles_controller.rb +++ b/app/controllers/api/v0/articles_controller.rb @@ -13,6 +13,7 @@ module Api def index @articles = ArticleApiIndexService.new(params).get + key_headers = [ "articles_api", params[:tag], @@ -25,12 +26,12 @@ module Api end def show + relation = Article.includes(:user).where(published: true) @article = if params[:id] == "by_path" - Article.includes(:user).find_by(path: params[:url])&.decorate + relation.find_by!(path: params[:url]).decorate else - Article.includes(:user).find(params[:id])&.decorate + relation.find(params[:id]).decorate end - not_found unless @article&.published end def onboarding diff --git a/spec/requests/api/v0/articles_spec.rb b/spec/requests/api/v0/articles_spec.rb index 302ba1eb5..1d7a5c1c1 100644 --- a/spec/requests/api/v0/articles_spec.rb +++ b/spec/requests/api/v0/articles_spec.rb @@ -65,11 +65,26 @@ RSpec.describe "Api::V0::Articles", type: :request do end describe "GET /api/articles/:id" do - it "data for article based on ID" do + it "gets article based on ID" do article = create(:article) get "/api/articles/#{article.id}" expect(JSON.parse(response.body)["title"]).to eq(article.title) end + + it "fails with an unpublished article" do + article = create(:article, published: false) + invalid_request = lambda do + get "/api/articles/#{article.id}" + end + expect(invalid_request).to raise_error(ActiveRecord::RecordNotFound) + end + + it "fails with an unknown article ID" do + invalid_request = lambda do + get "/api/articles/99999" + end + expect(invalid_request).to raise_error(ActiveRecord::RecordNotFound) + end end describe "POST /api/articles w/ current_user" do