add match history
This commit is contained in:
@@ -325,6 +325,72 @@ Action Cable использует формат JSON-сообщений чере
|
||||
|
||||
---
|
||||
|
||||
### История матчей
|
||||
|
||||
Возвращает постраничный список матчей текущего авторизованного пользователя, отсортированный от новых к старым (по дате начала `started_at`).
|
||||
|
||||
**URL:** `GET /api/matches`
|
||||
|
||||
**Auth:** требуется (JWT пользователя)
|
||||
|
||||
**Параметры query string:**
|
||||
|
||||
| Параметр | Тип | Обязательный | По умолчанию | Описание |
|
||||
|----------|-----|--------------|--------------|----------|
|
||||
| `start` / `from` | integer | — | `0` | Смещение (offset) от начала списка |
|
||||
| `count` | integer | — | `20` | Количество возвращаемых матчей (максимум 100) |
|
||||
|
||||
**Пример запроса:**
|
||||
|
||||
```bash
|
||||
curl -X GET "http://localhost:3000/api/matches?start=0&count=10" \
|
||||
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9..."
|
||||
```
|
||||
|
||||
**Успешный ответ (200 OK):**
|
||||
|
||||
```json
|
||||
{
|
||||
"matches": [
|
||||
{
|
||||
"id": "145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e2f",
|
||||
"status": "player1_won",
|
||||
"game_server": "ws://localhost:8081/ws",
|
||||
"started_at": "2026-11-09T12:00:00.000Z",
|
||||
"finished_at": "2026-11-09T12:02:05.000Z",
|
||||
"duration_seconds": 125,
|
||||
"player1": {
|
||||
"id": 1,
|
||||
"nickname": "CaptainNemo",
|
||||
"avatar_url": "http://localhost:3000/rails/active_storage/blobs/...",
|
||||
"rating_before": 100,
|
||||
"rating_change": 0
|
||||
},
|
||||
"player2": {
|
||||
"id": 2,
|
||||
"nickname": "CaptainHook",
|
||||
"avatar_url": null,
|
||||
"rating_before": 100,
|
||||
"rating_change": 0
|
||||
},
|
||||
"your_rating_before": 100,
|
||||
"your_rating_change": 0
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"start": 0,
|
||||
"count": 10
|
||||
}
|
||||
```
|
||||
|
||||
**Ошибки:**
|
||||
|
||||
| Код | Описание |
|
||||
|-----|----------|
|
||||
| `401` | отсутствует/невалиден токен |
|
||||
|
||||
---
|
||||
|
||||
### Детали матча
|
||||
|
||||
Возвращает подробную информацию о матче: итог, длительность и дельту рейтинга
|
||||
@@ -362,12 +428,14 @@ curl -X GET http://localhost:3000/api/matches/145575d6-3a4b-4c5d-9e6f-7a8b9c0d1e
|
||||
"player1": {
|
||||
"id": 1,
|
||||
"nickname": "CaptainNemo",
|
||||
"avatar_url": "http://localhost:3000/rails/active_storage/blobs/...",
|
||||
"rating_before": 100,
|
||||
"rating_change": 0
|
||||
},
|
||||
"player2": {
|
||||
"id": 2,
|
||||
"nickname": "CaptainHook",
|
||||
"avatar_url": null,
|
||||
"rating_before": 100,
|
||||
"rating_change": 0
|
||||
},
|
||||
|
||||
@@ -2,6 +2,29 @@
|
||||
# a non-participant (or an unknown uuid) gets 404 to avoid leaking
|
||||
# information about other players' matches.
|
||||
class Api::MatchesController < ApplicationController
|
||||
def index
|
||||
offset = (params[:start] || params[:from] || 0).to_i
|
||||
offset = 0 if offset < 0
|
||||
|
||||
count = params[:count].present? ? params[:count].to_i : 20
|
||||
count = 20 if count <= 0
|
||||
count = 100 if count > 100
|
||||
|
||||
scope = Match.for_user(current_user)
|
||||
.includes(player1: { avatar_attachment: :blob }, player2: { avatar_attachment: :blob })
|
||||
.order(started_at: :desc, id: :desc)
|
||||
|
||||
total = scope.count
|
||||
matches = scope.offset(offset).limit(count)
|
||||
|
||||
render json: {
|
||||
matches: matches.map { |match| MatchSerializer.as_json(match, viewer: current_user) },
|
||||
total: total,
|
||||
start: offset,
|
||||
count: count
|
||||
}
|
||||
end
|
||||
|
||||
def show
|
||||
match = Match.for_user(current_user).find_by(uuid: params[:uuid])
|
||||
return render json: { error: "Match not found" }, status: :not_found unless match
|
||||
|
||||
@@ -22,6 +22,13 @@ class User < ApplicationRecord
|
||||
.order(finished_at: :desc)
|
||||
end
|
||||
|
||||
def avatar_url
|
||||
return nil unless avatar.attached?
|
||||
|
||||
options = Rails.application.routes.default_url_options.presence || { host: "localhost", port: 3000 }
|
||||
Rails.application.routes.url_helpers.rails_blob_url(avatar, options)
|
||||
end
|
||||
|
||||
private
|
||||
def avatar_content_type
|
||||
unless avatar.blob.content_type.in?(%w[image/png image/jpeg image/gif image/webp])
|
||||
|
||||
@@ -32,6 +32,7 @@ class MatchSerializer
|
||||
{
|
||||
id: user.id,
|
||||
nickname: user.nickname,
|
||||
avatar_url: user.avatar_url,
|
||||
rating_before: rating_before,
|
||||
rating_change: rating_change
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ Rails.application.routes.draw do
|
||||
# (see app/channels/matchmaking_channel.rb).
|
||||
|
||||
# Match details for the participants of the match.
|
||||
get "matches", to: "matches#index"
|
||||
get "matches/:uuid", to: "matches#show"
|
||||
|
||||
# Intended for the game-server only; authenticated via HMAC (see
|
||||
|
||||
@@ -61,6 +61,23 @@ RSpec.describe User, type: :model do
|
||||
end
|
||||
end
|
||||
|
||||
describe "#avatar_url" do
|
||||
let(:user) { User.create!(valid_attributes) }
|
||||
|
||||
it "returns nil when avatar is not attached" do
|
||||
expect(user.avatar_url).to be_nil
|
||||
end
|
||||
|
||||
it "returns full url when avatar is attached" do
|
||||
user.avatar.attach(
|
||||
io: StringIO.new("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15c4"),
|
||||
filename: "avatar.png",
|
||||
content_type: "image/png"
|
||||
)
|
||||
expect(user.avatar_url).to include("avatar.png")
|
||||
end
|
||||
end
|
||||
|
||||
describe "rating" do
|
||||
it "defaults to the neutral initial value of 100" do
|
||||
expect(User.create!(valid_attributes).rating).to eq(100)
|
||||
|
||||
@@ -91,4 +91,129 @@ RSpec.describe "Match details API", type: :request do
|
||||
expect(json["match"]["duration_seconds"]).to be_nil
|
||||
end
|
||||
end
|
||||
|
||||
describe "GET /api/matches" do
|
||||
let!(:match1) do
|
||||
Match.create!(
|
||||
player1: player1,
|
||||
player2: player2,
|
||||
status: :player1_won,
|
||||
game_server: "ws://game-server:8080/ws",
|
||||
started_at: 20.minutes.ago,
|
||||
finished_at: 10.minutes.ago,
|
||||
duration_seconds: 600,
|
||||
player1_rating_before: 100,
|
||||
player2_rating_before: 100,
|
||||
player1_rating_change: 12,
|
||||
player2_rating_change: -12
|
||||
)
|
||||
end
|
||||
|
||||
let!(:match2) do
|
||||
Match.create!(
|
||||
player1: player2,
|
||||
player2: player1,
|
||||
status: :player2_won,
|
||||
game_server: "ws://game-server:8080/ws",
|
||||
started_at: 10.minutes.ago,
|
||||
finished_at: 5.minutes.ago,
|
||||
duration_seconds: 300,
|
||||
player1_rating_before: 88,
|
||||
player2_rating_before: 112,
|
||||
player1_rating_change: -10,
|
||||
player2_rating_change: 10
|
||||
)
|
||||
end
|
||||
|
||||
let!(:other_match) do
|
||||
Match.create!(
|
||||
player1: player2,
|
||||
player2: outsider,
|
||||
status: :player1_won,
|
||||
game_server: "ws://game-server:8080/ws",
|
||||
started_at: 5.minutes.ago,
|
||||
finished_at: Time.current,
|
||||
duration_seconds: 300,
|
||||
player1_rating_before: 100,
|
||||
player2_rating_before: 100,
|
||||
player1_rating_change: 15,
|
||||
player2_rating_change: -15
|
||||
)
|
||||
end
|
||||
|
||||
it "returns 401 without authentication" do
|
||||
get "/api/matches"
|
||||
|
||||
expect(response).to have_http_status(:unauthorized)
|
||||
end
|
||||
|
||||
it "returns the list of matches for current_user newest first" do
|
||||
get "/api/matches", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
|
||||
expect(json["total"]).to eq(2)
|
||||
expect(json["matches"].size).to eq(2)
|
||||
expect(json["matches"].first["id"]).to eq(match2.uuid)
|
||||
expect(json["matches"].second["id"]).to eq(match1.uuid)
|
||||
|
||||
first_item = json["matches"].first
|
||||
expect(first_item["your_rating_change"]).to eq(10)
|
||||
expect(first_item["player1"]["nickname"]).to eq("player_two")
|
||||
expect(first_item["player2"]["nickname"]).to eq("player_one")
|
||||
end
|
||||
|
||||
it "paginates results using start and count" do
|
||||
get "/api/matches?start=1&count=1", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
|
||||
expect(json["total"]).to eq(2)
|
||||
expect(json["start"]).to eq(1)
|
||||
expect(json["count"]).to eq(1)
|
||||
expect(json["matches"].size).to eq(1)
|
||||
expect(json["matches"].first["id"]).to eq(match1.uuid)
|
||||
end
|
||||
|
||||
it "supports from parameter as alias for start" do
|
||||
get "/api/matches?from=1&count=1", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
|
||||
expect(json["start"]).to eq(1)
|
||||
expect(json["matches"].size).to eq(1)
|
||||
expect(json["matches"].first["id"]).to eq(match1.uuid)
|
||||
end
|
||||
|
||||
it "returns an empty list when user has no matches" do
|
||||
get "/api/matches", headers: { "Authorization" => "Bearer #{token_for(outsider)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
|
||||
expect(json["total"]).to eq(1) # outsider has other_match
|
||||
expect(json["matches"].size).to eq(1)
|
||||
expect(json["matches"].first["id"]).to eq(other_match.uuid)
|
||||
end
|
||||
|
||||
it "includes player avatar_url if attached" do
|
||||
player1.avatar.attach(
|
||||
io: StringIO.new("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15c4"),
|
||||
filename: "avatar.png",
|
||||
content_type: "image/png"
|
||||
)
|
||||
|
||||
get "/api/matches", headers: { "Authorization" => "Bearer #{token_for(player1)}" }
|
||||
|
||||
expect(response).to have_http_status(:ok)
|
||||
json = JSON.parse(response.body)
|
||||
first_item = json["matches"].first
|
||||
# in match2, player1 is player2 and player2 is player1
|
||||
expect(first_item["player2"]["avatar_url"]).to include("avatar.png")
|
||||
expect(first_item["player1"]["avatar_url"]).to be_nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user