add private endpoint for match reporting
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
module Api
|
||||
module Internal
|
||||
# Receives match results reported by the game-server when a match ends.
|
||||
#
|
||||
# Transitions a match from `ongoing` to its final status and stores the
|
||||
# duration. Rating recalculation is not implemented yet, so the
|
||||
# rating_change fields stay as they are (0).
|
||||
#
|
||||
# The report is idempotent: re-reporting the same outcome for an already
|
||||
# finished match returns 200, a different one returns 409.
|
||||
class MatchResultsController < Api::Internal::BaseController
|
||||
FINAL_STATUSES = %w[player1_won player2_won draw abandoned].freeze
|
||||
|
||||
def create
|
||||
match = Match.find_by(uuid: params[:uuid])
|
||||
return render json: { error: "Match not found" }, status: :not_found unless match
|
||||
|
||||
status_param = params[:status].to_s
|
||||
unless FINAL_STATUSES.include?(status_param)
|
||||
return render json: { error: "status must be one of: #{FINAL_STATUSES.join(', ')}" },
|
||||
status: :unprocessable_content
|
||||
end
|
||||
|
||||
duration = parse_duration
|
||||
return render json: { error: "duration_seconds must be a non-negative integer" },
|
||||
status: :unprocessable_content if duration.nil?
|
||||
|
||||
unless match.ongoing?
|
||||
if match.status == status_param
|
||||
# Idempotent re-report of the same outcome.
|
||||
return render json: { match: MatchSerializer.as_json(match) }
|
||||
end
|
||||
|
||||
return render json: { error: "Match already finished" }, status: :conflict
|
||||
end
|
||||
|
||||
match.update!(status: status_param, duration_seconds: duration, finished_at: Time.current)
|
||||
render json: { match: MatchSerializer.as_json(match) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Accepts an integer or a string of digits; nil/floats/garbage are invalid.
|
||||
def parse_duration
|
||||
value = params[:duration_seconds]
|
||||
value = value.to_s if value.is_a?(Numeric)
|
||||
return nil unless value.is_a?(String) && value.match?(/\A\d+\z/)
|
||||
|
||||
value.to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user