diff --git a/Gemfile b/Gemfile index e4ba509..6823ebe 100644 --- a/Gemfile +++ b/Gemfile @@ -20,3 +20,5 @@ group :development, :test do end gem "faraday", "~> 2.14" + +gem "jbuilder", "~> 2.14" diff --git a/Gemfile.lock b/Gemfile.lock index 65ffb62..f680ae7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -102,6 +102,9 @@ GEM pp (>= 0.6.0) rdoc (>= 4.0.0) reline (>= 0.4.2) + jbuilder (2.14.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) json (2.15.1) logger (1.7.0) loofah (2.24.1) @@ -252,6 +255,7 @@ PLATFORMS DEPENDENCIES debug faraday (~> 2.14) + jbuilder (~> 2.14) puma (>= 5.0) rails (~> 8.0.3) rspec-rails (~> 8.0) diff --git a/app/controllers/api/v1/stats_controller.rb b/app/controllers/api/v1/stats_controller.rb new file mode 100644 index 0000000..5755150 --- /dev/null +++ b/app/controllers/api/v1/stats_controller.rb @@ -0,0 +1,9 @@ +module Api::V1 + class StatsController < BaseController + def index + @park_count = Park.count + @alert_count = Alert.count + @park_with_most_alerts = Alert.group(:park_code).count.max + end + end +end diff --git a/app/views/api/v1/stats/index.json.jbuilder b/app/views/api/v1/stats/index.json.jbuilder new file mode 100644 index 0000000..ecbd12e --- /dev/null +++ b/app/views/api/v1/stats/index.json.jbuilder @@ -0,0 +1,6 @@ +json.park_count @park_count +json.alert_count @alert_count +json.most_alerts do + json.park_code @park_with_most_alerts[0] + json.alert_count @park_with_most_alerts[1] +end diff --git a/config/routes.rb b/config/routes.rb index 49d0941..600d3f9 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,9 +1,10 @@ Rails.application.routes.draw do namespace :api do - namespace :v1 do + namespace :v1, defaults: { format: :json } do resources :parks, only: %i[index show], param: :code do resources :alerts, only: %i[index], module: :parks end + resources :stats, only: %i[index] end end # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html diff --git a/spec/requests/api/v1/stats_spec.rb b/spec/requests/api/v1/stats_spec.rb new file mode 100644 index 0000000..1e52b91 --- /dev/null +++ b/spec/requests/api/v1/stats_spec.rb @@ -0,0 +1,21 @@ +require 'rails_helper' + +RSpec.describe "Api::V1::Stats", type: :request do + describe "GET /stats" do + it "returns summary stats" do + alerts(:two).update!(park_code: parks(:one).code) + + get api_v1_stats_url + + expect(response).to have_http_status(:success) + expect(response.parsed_body).to match( + park_count: 2, + alert_count: 2, + most_alerts: { + park_code: "crla", + alert_count: 2 + } + ) + end + end +end