diff --git a/app/controllers/api/v1/posts_controller.rb b/app/controllers/api/v1/posts_controller.rb index 7330966..51e740a 100644 --- a/app/controllers/api/v1/posts_controller.rb +++ b/app/controllers/api/v1/posts_controller.rb @@ -1,8 +1,7 @@ -class Api::V1::PostsController < ApplicationController +class Api::V1::PostsController < Api::V1::ApplicationController - skip_before_action :verify_authenticity_token - before_action :authenticate_user_from_token - before_action :permit_params, only: [:create] + before_action :permit_params,:get_post, only: [:create] + before_action :load_post, only: [:add_viewed_times] after_action :process_post, only: :create @@ -12,9 +11,8 @@ class Api::V1::PostsController < ApplicationController } def create - @post = get_post if @current_user.share_instances.where(sharable: @post).empty? - share_instance = @current_user.share_instances.create sharable: @post, description: params[:description] + 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 @@ -28,6 +26,11 @@ class Api::V1::PostsController < ApplicationController 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 + private def permit_params @@ -35,13 +38,17 @@ class Api::V1::PostsController < ApplicationController end def get_post - Post.find_or_create_by!(url: params[:url], type: params[:type]) + begin + @post = Post.find_or_create_by!(url: params[:url], type: params[:type]) + rescue ActiveRecord::RecordInvalid + return render json: {msg: '缺少参数,校验失败'}, status: 400 + end + end def process_post unless @post.processed ProcessPostWorker.perform_async @post.url end - end end diff --git a/app/models/post.rb b/app/models/post.rb index ecf8ff8..a02aa14 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -4,4 +4,6 @@ class Post < ActiveRecord::Base has_many :likes, as: :likable has_many :favorites, as: :favoritable has_many :share_instances, as: :sharable + + validates_presence_of :url, :type end diff --git a/config/routes.rb b/config/routes.rb index 8bfc68c..b2bae73 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -78,6 +78,7 @@ Rails.application.routes.draw do resources :posts, only: [:create, :index, :show] do post :like, to: 'likes#like' post :unlike, to: 'likes#unlike' + post :view, to: 'posts#add_viewed_times' resources :comments, only: [:create, :show, :index, :destroy] do post :like, to: 'likes#comment_like'