From dd90e24d022bc2977b444803ae19691bf66ad8d3 Mon Sep 17 00:00:00 2001 From: Muhsin Keloth Date: Sun, 17 Jan 2021 09:15:31 -0800 Subject: [PATCH] chore: Add unread notification count API (#1646) Co-authored-by: Sojan --- .../v1/accounts/notifications_controller.rb | 5 ++++ config/routes.rb | 1 + .../accounts/notifications_controller_spec.rb | 25 +++++++++++++++++++ 3 files changed, 31 insertions(+) diff --git a/app/controllers/api/v1/accounts/notifications_controller.rb b/app/controllers/api/v1/accounts/notifications_controller.rb index 4a29f31c7..49191caad 100644 --- a/app/controllers/api/v1/accounts/notifications_controller.rb +++ b/app/controllers/api/v1/accounts/notifications_controller.rb @@ -27,6 +27,11 @@ class Api::V1::Accounts::NotificationsController < Api::V1::Accounts::BaseContro render json: @notification end + def unread_count + @unread_count = current_user.notifications.where(account_id: current_account.id, read_at: nil).count + render json: @unread_count + end + private def set_primary_actor diff --git a/config/routes.rb b/config/routes.rb index 06b8a4487..616da58a7 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -92,6 +92,7 @@ Rails.application.routes.draw do resources :notifications, only: [:index, :update] do collection do post :read_all + get :unread_count end end resource :notification_settings, only: [:show, :update] diff --git a/spec/controllers/api/v1/accounts/notifications_controller_spec.rb b/spec/controllers/api/v1/accounts/notifications_controller_spec.rb index fb92da8ad..3d824b841 100644 --- a/spec/controllers/api/v1/accounts/notifications_controller_spec.rb +++ b/spec/controllers/api/v1/accounts/notifications_controller_spec.rb @@ -102,4 +102,29 @@ RSpec.describe 'Notifications API', type: :request do end end end + + describe 'GET /api/v1/accounts/{account.id}/notifications/unread_count' do + context 'when it is an unauthenticated user' do + it 'returns unauthorized' do + get "/api/v1/accounts/#{account.id}/notifications/unread_count" + + expect(response).to have_http_status(:unauthorized) + end + end + + context 'when it is an authenticated user' do + let(:admin) { create(:user, account: account, role: :administrator) } + + it 'returns notifications unread count' do + 2.times.each { create(:notification, account: account, user: admin) } + get "/api/v1/accounts/#{account.id}/notifications/unread_count", + headers: admin.create_new_auth_token, + as: :json + + response_json = JSON.parse(response.body) + expect(response).to have_http_status(:success) + expect(response_json).to eq 2 + end + end + end end