GameLibrary/Controllers/GamesController.cs

70 lines
1.9 KiB
C#
Raw Normal View History

2024-10-03 14:22:21 +05:00
using GameLibrary.Models;
using GameLibrary.Repositories;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace GameLibrary.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GamesController : ControllerBase
{
private readonly IGameRepository _gameRepository;
public GamesController(IGameRepository gameRepository)
{
_gameRepository = gameRepository;
}
// GET: api/games
[HttpGet]
public async Task<ActionResult<IEnumerable<Game>>> GetGames(string genre = null)
{
var games = await _gameRepository.GetAllGames(genre);
return Ok(games);
}
// GET: api/games/{id}
[HttpGet("{id}")]
public async Task<ActionResult<Game>> GetGame(int id)
{
var game = await _gameRepository.GetGameById(id);
if (game == null)
{
return NotFound();
}
return Ok(game);
}
// POST: api/games
[HttpPost]
public async Task<ActionResult<Game>> CreateGame(Game game)
{
await _gameRepository.CreateGame(game);
return CreatedAtAction(nameof(GetGame), new { id = game.Id }, game);
}
// PUT: api/games/{id}
[HttpPut("{id}")]
public async Task<IActionResult> UpdateGame(int id, Game game)
{
if (id != game.Id)
{
return BadRequest();
}
await _gameRepository.UpdateGame(game);
return NoContent();
}
// DELETE: api/games/{id}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteGame(int id)
{
await _gameRepository.DeleteGame(id);
return NoContent();
}
}
}