Created
March 20, 2020 12:42
-
-
Save carlossanchezp/a6c6ab5e661335e351305f26466ac0d0 to your computer and use it in GitHub Desktop.
Example messages reading
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Api::V1::Chapters::MessagesController < Api::V1::ApiController | |
before_action :set_chapter, only: :index | |
before_action :set_current_user_from_token, only: :index | |
before_action :set_or_create_guest_from_identifier, only: :index | |
before_action :check_if_max_messages_exceeded, only: :index | |
before_action :increment_messages_count, only: :index | |
api :GET, '/v1/chapters/:chapter_id/messages', "Messages from chapter (with pages)" | |
param_group :app_headers, Api::V1::ApiController | |
param :story_id, Integer, required: true | |
param :page, Integer | |
error :code => 404, :desc => "Chapter not found" | |
error :code => 403, :desc => "The guest has exceeded the maximum number of free messages" | |
error :code => 400, :desc => "Guest identifider or user token is required" | |
def index | |
messages = @chapter | |
.messages | |
.includes(:character, :attachment) | |
.paginate(page: params[:page], per_page: Message::ITEMS_PER_PAGE) | |
.order(created_at: :asc) | |
create_chapter_request(params[:page] || 1) | |
render(json: messages, | |
each_serializer: Api::V1::MessageToListSerializer, | |
scope: @current_user, | |
meta: pagination_dict(messages) | |
) | |
end | |
private | |
def set_chapter | |
@chapter = Chapter.find_by(id: params[:chapter_id]) | |
render_404('Chapter') unless @chapter | |
end | |
def check_if_max_messages_exceeded | |
return if @current_user | |
unless @guest | |
render_400('Guest identifider or user token is required') | |
return | |
end | |
if @guest.read_messages_count > AppConfiguration.first.max_messages_before_sign_in | |
render_403('The guest has exceeded the maximum number of free messages') | |
end | |
end | |
def increment_messages_count | |
return @current_user.increment!(:read_messages_count, Message::ITEMS_PER_PAGE) if @current_user | |
@guest.increment!(:read_messages_count, Message::ITEMS_PER_PAGE) | |
end | |
def create_chapter_request(page) | |
get_owner = @current_user || @guest | |
type_user = get_type_user_or_guest(get_owner) | |
StoriesHardWorker.perform_async("reading",@chapter.story_id,get_owner.id,type_user) | |
ChapterRequest.create( | |
story_id: @chapter.story_id, | |
chapter: @chapter, | |
owner: get_owner, | |
page: page | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment