Add GET /api/v1/notices and DELETE /api/v1/notices/:id

This commit is contained in:
Claire 2023-09-11 14:21:19 +02:00
parent 898800198a
commit 84f6050817
4 changed files with 73 additions and 0 deletions

View file

@ -0,0 +1,27 @@
# frozen_string_literal: true
class Api::V1::NoticesController < Api::BaseController
before_action -> { doorkeeper_authorize! :write, :'write:accounts' }, only: :destroy
before_action :require_user!
before_action :set_notices, only: :index
before_action :set_notice, except: :index
def index
render json: @notices, each_serializer: REST::NoticeSerializer
end
def destroy
@notice.dismiss_for_user!(current_user)
render_empty
end
private
def set_notices
@notices = [Notice.first_unseen(current_user)].compact
end
def set_notice
@notice = Notice.find(params[:id])
end
end

33
app/models/notice.rb Normal file
View file

@ -0,0 +1,33 @@
# frozen_string_literal: true
class Notice < ActiveModelSerializers::Model
attributes :id, :icon, :title, :message, :actions
# Notices a user has seen are stored as a bitmap in
# `users.seen_notifications`.
NOTICE_BIT_MAP = {}.freeze
def dismiss_for_user!(user)
user.update!(seen_notices: (user.seen_notices || 0) | NOTICE_BIT_MAP[id])
end
class Action < ActiveModelSerializers::Model
attributes :label, :url
end
class << self
include RoutingHelper
def first_unseen(user)
notice_key = NOTICE_BIT_MAP.find { |_, bit| ((user.seen_notices || 0) & bit).zero? }&.first
send("#{notice_key}_notice") if notice_key.present?
end
def find(key)
throw ActiveRecord::RecordNotFound unless NOTICE_BIT_MAP.key?(key.to_sym)
send("#{key}_notice")
end
end
end

View file

@ -0,0 +1,11 @@
# frozen_string_literal: true
class REST::NoticeSerializer < ActiveModel::Serializer
class ActionSerializer < ActiveModel::Serializer
attributes :label, :url
end
attributes :id, :icon, :title, :message
has_many :actions, serializer: ActionSerializer
end

View file

@ -61,6 +61,8 @@ namespace :api, format: false do
end
end
resources :notices, only: [:index, :destroy]
# namespace :crypto do
# resources :deliveries, only: :create