-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScoresController.cs
More file actions
65 lines (54 loc) · 1.81 KB
/
Copy pathScoresController.cs
File metadata and controls
65 lines (54 loc) · 1.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.EntityFrameworkCore;
using Qwertide.Api.Data;
using Qwertide.Api.Models;
namespace Qwertide.Api.Controllers;
/// <summary>
/// Leaderboard endpoints (PDD §6):
/// GET /api/scores?top=10 - top N entries by WPM, then accuracy
/// POST /api/scores - submit a new score
/// </summary>
[ApiController]
[Route("api/[controller]")]
public sealed class ScoresController : ControllerBase
{
private const int MaxTop = 100;
private readonly QwertideDbContext _db;
public ScoresController(QwertideDbContext db) => _db = db;
[HttpGet]
public async Task<ActionResult<IReadOnlyList<Score>>> GetTop([FromQuery] int top = 10)
{
top = Math.Clamp(top, 1, MaxTop);
var scores = await _db.Scores
.OrderByDescending(s => s.Wpm)
.ThenByDescending(s => s.Accuracy)
.ThenBy(s => s.DurationSecs)
.Take(top)
.ToListAsync();
return Ok(scores);
}
[HttpGet("{id:int}")]
public async Task<ActionResult<Score>> GetById(int id)
{
var score = await _db.Scores.FindAsync(id);
return score is null ? NotFound() : Ok(score);
}
[HttpPost]
[EnableRateLimiting("submit")]
public async Task<ActionResult<Score>> Submit([FromBody] ScoreRequest request)
{
var score = new Score
{
PlayerName = request.PlayerName.Trim(),
Wpm = request.Wpm,
Accuracy = request.Accuracy,
DurationSecs = request.DurationSecs,
PassageId = request.PassageId,
CreatedAtUtc = DateTime.UtcNow,
};
_db.Scores.Add(score);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(GetById), new { id = score.Id }, score);
}
}