Files
libr-2/app/controllers/api/v1/posts_controller.rb
T

86 lines
2.3 KiB
Ruby

class Api::V1::PostsController < Api::V1::ApplicationController
before_action :permit_params, :map_post_type, :get_post, only: [:create]
before_action :load_post, only: [:add_viewed_times, :show]
skip_before_action :authenticate_user_from_token, only: [:show]
before_action :fetch_current_user
after_action :process_post, only: :create
POST_TYPE = {
:ARTICLE => 'article',
:WEB_PAGE => 'web_page'
}
def create
if @current_user.share_instances.where(sharable: @post).empty?
share_instance = @current_user.share_instances.create! sharable: @post, description: params[:description]
render json: share_instance.to_json(include: :sharable)
else
render json: {message: '请勿重复分享同一资源'}, status: 409
end
end
def show
render json: @target_post, serializer: PostSerializer
end
def index
render json: @current_user.share_instances.page(params[:page]), each_serializer: ShareInstanceSerializer
end
def add_viewed_times
@target_post.increment!(:viewed_times)
render nothing: true
end
def liked_posts
ids = Like.where(user_id: @current_user.id).order(:created_at).pluck(:likable_id)
render json: Post.where(id: ids).page(params[:page]), each_serializer: EachPostSerializer
end
def bookmarked_posts
ids = Favorite.where(user_id: @current_user.id).order(:created_at).pluck(:favoritable_id)
render json: Post.where(id: ids).page(params[:page]), each_serializer: EachPostSerializer
end
def search
params.permit(:keywords)
render json: Post.where('title LIKE ?',"%#{params[:keywords]}%").page(params[:page]), each_serializer: EachPostSerializer
end
private
def permit_params
params.permit(:url, :type, :description)
end
def get_post
begin
@post = Post.find_or_create_by!(url: params[:url], type: @type)
rescue ActiveRecord::RecordInvalid
return render json: {msg: '缺少参数,校验失败'}, status: 400
end
end
def map_post_type
case params[:type]
when 'article'
@type = 'Article'
when 'page'
@type = 'WebPage'
else
return render json: {msg: 'Post 类型不合法'}, status: 400
end
end
def process_post
unless @post.processed
ProcessPostWorker.perform_async @post.url
end
end
end