feat: add api controller

GET, POST, PUT method is present. DELETE is absent scince we don't need it in this case
This commit is contained in:
cuqmbr 2022-07-15 20:47:22 +03:00
parent 9c76d4965b
commit 3d170dca7a
4 changed files with 88 additions and 3 deletions

View File

@ -0,0 +1,82 @@
using DatabaseModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Server.Data;
namespace Server.Controllers;
[Route("api/[controller]")]
[ApiController]
public class ScoreboardController : ControllerBase
{
private readonly ServerDbContext _context;
public ScoreboardController(ServerDbContext context)
{
_context = context;
}
// GET: api/Scoreboard
[HttpGet]
public async Task<ActionResult<ScoreboardRecord[]>> Get()
{
return await _context.Scoreboard.ToArrayAsync();
}
// GET: api/Scoreboard/cuqmbr
[HttpGet("{username}", Name = "Get")]
public async Task<ActionResult<ScoreboardRecord>> Get(string username)
{
var sbRecord = await _context.Scoreboard.FirstOrDefaultAsync(sbr => sbr.Username == username);
if (sbRecord == null)
{
return NotFound();
}
return sbRecord;
}
// POST: api/Scoreboard
[HttpPost]
public async Task<ActionResult> Post([FromBody] ScoreboardRecord sbRecord)
{
await _context.AddAsync(sbRecord);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(Get), new {sbRecord.Username}, sbRecord);
}
// PUT: api/Scoreboard/cuqmbr
[HttpPut("{username}")]
public async Task<ActionResult> Put(string username, [FromBody] ScoreboardRecord sbRecord)
{
if (username != sbRecord.Username)
{
return BadRequest();
}
_context.Entry(sbRecord).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!await ScoreboardRecordExists(sbRecord.Username))
{
return NotFound();
}
throw;
}
return NoContent();
}
private async Task<bool> ScoreboardRecordExists(string username)
{
return await _context.Scoreboard.AnyAsync(sbr => sbr.Username == username);
}
}

View File

@ -8,7 +8,7 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddDbContext<ServerDbContext>(o => o.UseSqlite());
builder.Services.AddDbContext<ServerDbContext>(o => o.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();

View File

@ -13,7 +13,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"launchUrl": "",
"applicationUrl": "https://localhost:7248;http://localhost:5214",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
@ -22,7 +22,7 @@
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"launchUrl": "",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -1,4 +1,7 @@
{
"ConnectionStrings": {
"DefaultConnection": "Filename=./Scoreboard-SQLite.db"
},
"Logging": {
"LogLevel": {
"Default": "Information",