Files
spacerace/Server/Controllers/LapController.cs
T
2023-08-30 20:21:08 +10:00

76 lines
1.9 KiB
C#

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;
using Server.Services;
using SpaceRace.Shared;
namespace Server.Controllers;
[ApiController]
[Route("[controller]")]
public class LapController : ControllerBase {
private readonly ILogger<LapController> _logger;
private SpaceRaceDbContext _db;
private LapTimesService _lapTimes;
public LapController(
ILogger<LapController> logger,
SpaceRaceDbContext db,
LapTimesService lapTimes
){
_logger = logger;
_db = db;
_lapTimes = lapTimes;
}
[HttpGet()]
public IEnumerable<LapDTO> Get() {
return _db.Laps.Select(c => new LapDTO {
Id = c.Id,
UserId = c.UserId,
Map = c.Map,
Time = c.Time,
Created = c.Created,
});
}
[HttpPost()]
public async Task<LapTimesDTO> Post(LapDTO dto) {
Lap existing = _db.Laps
.SingleOrDefault(l => l.UserId == dto.UserId && l.Map == dto.Map);
Lap NotFaster(Lap e) {
_logger.LogInformation($"Lap was not a PB.");
return e;
}
Lap UpdateValues(Lap e) => new Lap {
Id = e.Id,
UserId = e.UserId,
Map = e.Map,
Time = dto.Time,
Sectors = dto.Sectors,
Created = DateTimeOffset.Now,
};
Lap Create() => new Lap {
Id = Guid.NewGuid(),
UserId = dto.UserId,
Map = dto.Map,
Time = dto.Time,
Sectors = dto.Sectors,
Created = DateTimeOffset.UtcNow,
};
Lap v = existing switch {
null => Create(),
Lap e when dto.Time < e.Time => UpdateValues(e),
_ => NotFaster(existing),
};
await _db.Laps.Upsert(v).RunAsync();
return _lapTimes.LapTimes(v.UserId, v.Map);
}
}