diff --git a/app/controllers/api/v0/github_repos_controller.rb b/app/controllers/api/v0/github_repos_controller.rb index 6afc1ab67..d9e9a5e27 100644 --- a/app/controllers/api/v0/github_repos_controller.rb +++ b/app/controllers/api/v0/github_repos_controller.rb @@ -16,7 +16,13 @@ module Api def update_or_create @client = create_octokit_client - @repo = GithubRepo.find_or_create(fetched_repo_params) + fetched_repo = fetch_repo + unless fetched_repo + render json: "error: Could not find Github repo", status: :not_found + return + end + + @repo = GithubRepo.find_or_create(fetched_repo_params(fetched_repo)) current_user.touch(:github_repos_updated_at) if @repo.valid? render json: { featured: @repo.featured } @@ -32,11 +38,7 @@ module Api Octokit::Client.new(access_token: current_user_token) end - def fetched_repo_params - params[:github_repo] = JSON.parse(params[:github_repo]) - fetched_repo = @client.repositories.detect do |repo| - repo.id == permitted_attributes(GithubRepo)[:github_id_code].to_i - end + def fetched_repo_params(fetched_repo) { github_id_code: fetched_repo.id, user_id: current_user.id, @@ -52,6 +54,13 @@ module Api info_hash: fetched_repo.to_hash } end + + def fetch_repo + params[:github_repo] = JSON.parse(params[:github_repo]) + @client.repositories.detect do |repo| + repo.id == permitted_attributes(GithubRepo)[:github_id_code].to_i + end + end end end end diff --git a/spec/requests/api/v0/github_repos_spec.rb b/spec/requests/api/v0/github_repos_spec.rb index f3d73f2f6..5783efb77 100644 --- a/spec/requests/api/v0/github_repos_spec.rb +++ b/spec/requests/api/v0/github_repos_spec.rb @@ -35,5 +35,13 @@ RSpec.describe "Api::V0::GithubRepos", type: :request do expect(response).to have_http_status(:ok) expect(response.content_type).to eq("application/json") end + + it "returns 404 and json response on error" do + allow(Octokit::Client).to receive(:new).and_return(my_ocktokit_client) + allow(my_ocktokit_client).to receive(:repositories).and_return([]) + post "/api/github_repos/update_or_create", params: { github_repo: "{}" } + expect(response).to have_http_status(:not_found) + expect(response.body).to include("Could not find Github repo") + end end end