CodeLiturgy.Dashboard/BlueWest.Api/Controllers/CurrencyController.cs

106 lines
3.6 KiB
C#

using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using BlueWest.Data;
using BlueWest.WebApi.MySQL;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
/// <summary>
/// The controller responsible to fetch currency data
/// </summary>
[ApiController]
[Route("[controller]")]
public class CurrencyController : ControllerBase
{
private readonly CountriesDbContext _dbContext;
public CurrencyController(CountriesDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Gets the currency data from currency table
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetCurrencies()
{
var dbContext = _dbContext.Currencies;
if (dbContext != null)
{
return Ok(dbContext.ToArray());
}
return new NotFoundResult();
}
/// <summary>
/// Add Currency to the table of currencies
/// </summary>
/// <param name="currencyToCreate">Currency data to create</param>
/// <param name="currencyAssociatedCountries">Countries</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddCurrency(CurrencyCreate currencyToCreate)
{
var newCurrency = currencyToCreate.ToCurrency();
_dbContext.Currencies.Add(newCurrency);
_dbContext.SaveChanges();
return CreatedAtRoute(nameof(GetCurrencyById), new {CurrencyId = newCurrency.Code}, newCurrency);
}
/// <summary>
/// Update a currency data from the Currency table in the database
/// </summary>
/// <param name="currencyNumber">The currency number we want to update</param>
/// <param name="currencyToUpdate">Currency Data to update</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut("{currencyNumber}")]
public ActionResult UpdateCurrency(int currencyNumber, CurrencyUpdate currencyToUpdate)
{
var currency = _dbContext.Currencies.FirstOrDefault(x => x.Num == currencyNumber);
if (currency != null)
{
var updatedCurrency = new Currency(currencyToUpdate, currencyNumber, new List<Country>());
_dbContext.Update(updatedCurrency);
_dbContext.SaveChanges();
return Ok(updatedCurrency);
}
return new NotFoundResult();
}
/// <summary>
/// Gets a currency by the currency number (id)
/// </summary>
/// <param name="currencyId">The id of the currency to get</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{currencyId}", Name = nameof(GetCurrencyById))]
public ActionResult GetCurrencyById(int currencyId)
{
var array = _dbContext.Countries.FirstOrDefault(x => x.Code == currencyId);
if (array != null)
{
return Ok(array);
}
return new NotFoundResult();
}
}
}