Data objects working in controllers (Country and Currency)

This commit is contained in:
CodeLiturgy 2022-08-22 03:13:53 +01:00
parent 8dfd6e80cc
commit ee42714069
12 changed files with 141 additions and 108 deletions

View File

@ -12,24 +12,24 @@ namespace BlueWest.WebApi.EF
public sealed class CompanyDbContext : DbContext public sealed class CompanyDbContext : DbContext
{ {
/// <summary> /// <summary>
/// Db set of Companies /// Companies.
/// </summary> /// </summary>
public DbSet<Company> Companies { get; set; } public DbSet<Company> Companies { get; set; }
/// <summary> /// <summary>
/// Db set of Industries. /// Industries.
/// </summary> /// </summary>
public DbSet<Industry> Industries { get; set; } public DbSet<Industry> Industries { get; set; }
/// <summary> /// <summary>
/// Db set of Products. /// Products.
/// </summary> /// </summary>
public DbSet<Product> Products { get; set; } public DbSet<Product> Products { get; set; }
/// <summary> /// <summary>
/// Options to be injected in the app /// CompanyDbContext constructor.
/// </summary> /// </summary>
/// <param name="options"></param> /// <param name="options"></param>
public CompanyDbContext(DbContextOptions<CompanyDbContext> options) : base(options) public CompanyDbContext(DbContextOptions<CompanyDbContext> options) : base(options)
@ -38,7 +38,7 @@ namespace BlueWest.WebApi.EF
} }
/// <summary> /// <summary>
/// On database model creating /// On model creating.
/// </summary> /// </summary>
/// <param name="modelBuilder">Builder model of the database</param> /// <param name="modelBuilder">Builder model of the database</param>
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)

View File

@ -29,7 +29,7 @@ namespace BlueWest.WebApi.EF
/// <summary> /// <summary>
/// Options to be injected in the app /// CountryDbContext Constructor.
/// </summary> /// </summary>
/// <param name="options"></param> /// <param name="options"></param>
public CountryDbContext(DbContextOptions<CountryDbContext> options) : base(options) public CountryDbContext(DbContextOptions<CountryDbContext> options) : base(options)
@ -38,8 +38,7 @@ namespace BlueWest.WebApi.EF
} }
/// <summary> /// <summary>
/// The country number is the primary key /// On model creating.
/// The currency code is the primary key
/// </summary> /// </summary>
/// <param name="modelBuilder"></param> /// <param name="modelBuilder"></param>
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)

View File

@ -24,13 +24,12 @@ namespace BlueWest.WebApi.Interfaces
#region Initialization #region Initialization
/// <summary> /// <summary>
/// Exchange Interface Object /// Database Ef context constructor
/// </summary> /// </summary>
/// <param name="countryDbContext">Country context</param> /// <param name="countryDbContext">Country context</param>
/// <param name="financeDbContext">Finance context</param> /// <param name="financeDbContext">Finance context</param>
/// <param name="userDbContext">User context</param> /// <param name="userDbContext">User context</param>
/// <param name="eventManager">Event manager injection</param> /// <param name="eventManager">Event manager injection</param>
public ExchangeInterface( public ExchangeInterface(
CountryDbContext countryDbContext, CountryDbContext countryDbContext,
@ -46,7 +45,7 @@ namespace BlueWest.WebApi.Interfaces
} }
/// <summary> /// <summary>
/// Empty constructor /// Database Ef context constructor
/// </summary> /// </summary>
public ExchangeInterface() { } public ExchangeInterface() { }

View File

@ -92,7 +92,13 @@ namespace BlueWest.WebApi.EF
int countryId, CurrencyCreate currencyCreate, int countryId, CurrencyCreate currencyCreate,
Expression<Func<Currency,bool>>[] duplicationValidations) Expression<Func<Currency,bool>>[] duplicationValidations)
{ {
var country = dbContext.Countries.FirstOrDefault(d => d.Id == countryId);
var country = dbContext
.Countries
.Where(data => data.Id == countryId)
.Include(o => o.Currencies)
.FirstOrDefault();
// Check if currency exists // Check if currency exists
if (country == null) return (false, $"{nameof(country)} Not found.", null); if (country == null) return (false, $"{nameof(country)} Not found.", null);

View File

@ -20,7 +20,7 @@ namespace BlueWest.WebApi.EF
public DbSet<FinanceOpType> TransactionTypes { get; set; } public DbSet<FinanceOpType> TransactionTypes { get; set; }
/// <summary> /// <summary>
/// Finance transactions context /// CompanyDbContext constructor.
/// </summary> /// </summary>
/// <param name="options"></param> /// <param name="options"></param>
public FinanceDbContext(DbContextOptions<FinanceDbContext> options) : base(options) public FinanceDbContext(DbContextOptions<FinanceDbContext> options) : base(options)
@ -29,7 +29,7 @@ namespace BlueWest.WebApi.EF
} }
/// <summary> /// <summary>
/// On database model creating /// On model creating.
/// </summary> /// </summary>
/// <param name="modelBuilder">Builder model of the database</param> /// <param name="modelBuilder">Builder model of the database</param>
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)

View File

@ -31,7 +31,7 @@ namespace BlueWest.WebApi.EF
} }
/// <summary> /// <summary>
/// On database model creating /// On model creating.
/// </summary> /// </summary>
/// <param name="modelBuilder">Builder model of the database</param> /// <param name="modelBuilder">Builder model of the database</param>
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)

View File

@ -27,7 +27,77 @@ namespace BlueWest.WebApi.Controllers
_dbContext = dbContext; _dbContext = dbContext;
} }
/// <summary>
/// Get countries
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetCountries()
{
var array = _dbContext
.Countries
.Select(x => new CountryUnique(x))
.ToArray();
return Ok(array);
}
/// <summary>
/// Get Country by Id
/// </summary>
/// <param name="countryId">ISO 3166-1 countryId numeric code</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}", Name = nameof(GetCountryById))]
public ActionResult GetCountryById(int countryId)
{
var country = _dbContext.Countries
.Where(x => x.Id == countryId)
.Select(x => new CountryUnique(x))
.FirstOrDefault();
if (country != null)
{
return Ok(country);
}
return new NotFoundResult();
}
/// <summary>
/// Get currencies of a countryId
/// </summary>
/// <param name="countryId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}/currencies")]
public ActionResult GetCountryCurrencies(int countryId)
{
var countryObj = _dbContext.Countries.FirstOrDefault(d => d.Id == countryId);
if (countryObj == null) return new NotFoundResult();
var array = _dbContext
.Countries
.Where(data => data.Id == countryId)
.SelectMany(o => o.Currencies)
.Select(x => new CurrencyUnique(x))
.ToArray();
return Ok(array);
}
/// <summary> /// <summary>
/// Add Country /// Add Country
/// </summary> /// </summary>
@ -54,12 +124,11 @@ namespace BlueWest.WebApi.Controllers
[HttpPost] [HttpPost]
public ActionResult AddCountry(CountryCreate countryToCreate) public ActionResult AddCountry(CountryCreate countryToCreate)
{ {
Country newCountry = new Country(countryToCreate); Country newCountry = new Country(countryToCreate);
_dbContext.Countries.Add(newCountry); _dbContext.Countries.Add(newCountry);
bool success = _dbContext.SaveChanges() >= 0; bool success = _dbContext.SaveChanges() >= 0;
if (!success) return new BadRequestResult(); if (!success) return new BadRequestResult();
return CreatedAtRoute(nameof(GetCountryById), new {countryId = newCountry.Id}); return CreatedAtRoute(nameof(GetCountryById), new {countryId = newCountry.Id}, new CountryUnique(newCountry));
} }
/// <summary> /// <summary>
@ -73,80 +142,18 @@ namespace BlueWest.WebApi.Controllers
[HttpPut("{countryCode}")] [HttpPut("{countryCode}")]
public ActionResult UpdateCountry(int countryCode, CountryUpdate countryToUpdate) public ActionResult UpdateCountry(int countryCode, CountryUpdate countryToUpdate)
{ {
var (success, countryId) = _dbContext.UpdateCountry(countryToUpdate, countryCode); var (success, country) = _dbContext.UpdateCountry(countryToUpdate, countryCode);
if (success) if (success)
{ {
return Ok(countryId); var countryReply = new CountryUnique(country);
return Ok(countryReply);
} }
return new NotFoundResult(); return new NotFoundResult();
} }
/// <summary>
/// Get countries
/// </summary>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetCountries()
{
var array = _dbContext.Countries;
if (array != null)
{
return Ok(array.ToArray());
}
return new NotFoundResult();
}
/// <summary>
/// Get Country by Id
/// </summary>
/// <param name="countryId">ISO 3166-1 countryId numeric code</param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}", Name = nameof(GetCountryById))]
public ActionResult GetCountryById(int countryId)
{
var array = _dbContext.Countries.FirstOrDefault(x => x.Id == countryId);
if (array != null)
{
return Ok(array);
}
return new NotFoundResult();
}
/// <summary>
/// Get currencies of a countryId
/// </summary>
/// <param name="countryId"></param>
/// <returns></returns>
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}/currencies")]
public ActionResult GetCountryCurrencies(int countryId)
{
var countryObj = _dbContext.Countries.FirstOrDefault(d => d.Id == countryId);
if (countryObj == null) return new NotFoundResult();
var array = _dbContext
.Countries
.Where(data => data.Id == countryId)
.SelectMany(o => o.Currencies)
.ToArray();
return Ok(array);
}
/// <summary> /// <summary>
/// Adds a currency to Country /// Adds a currency to Country
/// </summary> /// </summary>
@ -170,7 +177,7 @@ namespace BlueWest.WebApi.Controllers
return new ConflictObjectResult(message); return new ConflictObjectResult(message);
} }
return Ok(country); return Ok(new CountryUnique(country));
} }

View File

@ -35,7 +35,10 @@ namespace BlueWest.WebApi.Controllers
[HttpGet] [HttpGet]
public ActionResult GetCurrencies() public ActionResult GetCurrencies()
{ {
var currencies = _dbContext.Currencies.ToArray(); var currencies = _dbContext.Currencies
.Select(currency => new CurrencyUnique(currency))
.ToArray();
return Ok(currencies); return Ok(currencies);
} }
@ -56,7 +59,7 @@ namespace BlueWest.WebApi.Controllers
return new NotFoundResult(); return new NotFoundResult();
} }
return CreatedAtRoute(nameof(GetCurrencyById), new {CurrencyId = newCurrency.Code}, newCurrency); return CreatedAtRoute(nameof(GetCurrencyById), new {CurrencyId = newCurrency.Code}, new CurrencyUnique(newCurrency));
} }
/// <summary> /// <summary>
@ -74,7 +77,7 @@ namespace BlueWest.WebApi.Controllers
if (success) if (success)
{ {
return Ok(currency); return Ok(new CurrencyUnique(currency));
} }
return new NotFoundResult(); return new NotFoundResult();
@ -95,7 +98,7 @@ namespace BlueWest.WebApi.Controllers
if (currency != null) if (currency != null)
{ {
return Ok(currency); return Ok(new CurrencyUnique(currency));
} }
return new NotFoundResult(); return new NotFoundResult();

View File

@ -7,8 +7,29 @@ WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src WORKDIR /src
COPY ["BlueWest.Data.Capital/BlueWest.Data.Capital.csproj", "BlueWest.Data.Capital/"]
RUN dotnet restore "BlueWest.Data.Capital/BlueWest.Data.Capital.csproj"
COPY ["BlueWest/BlueWest.csproj", "BlueWest/"]
RUN dotnet restore "BlueWest/BlueWest.csproj"
COPY ["BlueWest.Data.Geography/BlueWest.Data.Geography.csproj", "BlueWest.Data.Geography/"]
RUN dotnet restore "BlueWest.Data.Geography/BlueWest.Data.Geography.csproj"
COPY ["BlueWest.Api/BlueWest.Api.csproj", "BlueWest.Api/"] COPY ["BlueWest.Api/BlueWest.Api.csproj", "BlueWest.Api/"]
RUN dotnet restore "BlueWest.Api/BlueWest.Api.csproj" RUN dotnet restore "BlueWest.Api/BlueWest.Api.csproj"
COPY ["include/BlueWest.MapTo/src/BlueWest.MapTo/BlueWest.MapTo.csproj", "include/BlueWest.MapTo/src/BlueWest.MapTo/"]
RUN dotnet restore "include/BlueWest.MapTo/src/BlueWest.MapTo/BlueWest.MapTo.csproj"
COPY ["include/Math-Expression-Evaluator/SimpleExpressionEvaluator/SimpleExpressionEvaluator.csproj", "include/Math-Expression-Evaluator/SimpleExpressionEvaluator/"]
RUN dotnet restore "include/Math-Expression-Evaluator/SimpleExpressionEvaluator/SimpleExpressionEvaluator.csproj"
COPY [".", "."] COPY [".", "."]
RUN dotnet build "BlueWest.Api/BlueWest.Api.csproj" -c Release -o /app/build RUN dotnet build "BlueWest.Api/BlueWest.Api.csproj" -c Release -o /app/build

View File

@ -25,20 +25,22 @@ namespace BlueWest.WebApi
IConfiguration configuration, IConfiguration configuration,
IWebHostEnvironment environment) IWebHostEnvironment environment)
{ {
var optionsBuilderRef = optionsBuilder.UseMySql(configuration.GetConnectionString("LocalMySQL"), optionsBuilder.UseMySql(configuration.GetConnectionString("LocalMySQL"),
new MySqlServerVersion(new Version(8, 0, 11))); new MySqlServerVersion(new Version(8, 0, 11)))
.UseMySql(new MySqlServerVersion(new Version(8, 0, 11)),
builder => { builder.EnableRetryOnFailure(6, TimeSpan.FromSeconds(3), null); });
// The following three options help with debugging, but should // The following three options help with debugging, but should
// be changed or removed for production. // be changed or removed for production.
if (environment.IsDevelopment()) if (environment.IsDevelopment())
{ {
optionsBuilderRef optionsBuilder
.LogTo(Console.WriteLine, LogLevel.Information) .LogTo(Console.WriteLine, LogLevel.Information)
.EnableSensitiveDataLogging() .EnableSensitiveDataLogging()
.EnableDetailedErrors(); .EnableDetailedErrors();
} }
return optionsBuilderRef; return optionsBuilder;
} }
/// <summary> /// <summary>
@ -51,14 +53,11 @@ namespace BlueWest.WebApi
public static IServiceCollection PrepareDatabasePool(this IServiceCollection serviceCollection, public static IServiceCollection PrepareDatabasePool(this IServiceCollection serviceCollection,
IConfiguration configuration, IWebHostEnvironment environment) IConfiguration configuration, IWebHostEnvironment environment)
{ {
return serviceCollection return serviceCollection
.AddDbContextPool<UserDbContext>(options => options.GetMySqlSettings(configuration, environment)) .AddDbContextPool<UserDbContext>(options => options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<CountryDbContext>(options => options.GetMySqlSettings(configuration, environment)) .AddDbContextPool<CountryDbContext>(options => options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<FinanceDbContext>(options => options.GetMySqlSettings(configuration, environment)) .AddDbContextPool<FinanceDbContext>(options => options.GetMySqlSettings(configuration, environment))
.AddDbContextPool<CompanyDbContext>(options => options.GetMySqlSettings(configuration, environment)); .AddDbContextPool<CompanyDbContext>(options => options.GetMySqlSettings(configuration, environment));
} }
} }
} }

View File

@ -7,6 +7,7 @@ namespace BlueWest.Data
[MapFrom(typeof(Currency))] [MapFrom(typeof(Currency))]
public partial class CurrencyUnique public partial class CurrencyUnique
{ {
public int Id { get; set; }
public int Num { get; set; } // Primary key public int Num { get; set; } // Primary key
[MaxLength(3)] public string Code { get; set; } [MaxLength(3)] public string Code { get; set; }

View File

@ -1,17 +1,5 @@
version: '3' version: '3'
services: services:
bapi120:
build:
context: ./
dockerfile: ./BlueWest.Api/Dockerfile
ports:
- 8080:80
environment:
VIRTUAL_HOST: localhost
restart: always
links:
- db:db
container_name: BW1_API
db: db:
container_name: BW1_DB_MYSQL container_name: BW1_DB_MYSQL
image: mysql/mysql-server:8.0 image: mysql/mysql-server:8.0
@ -34,7 +22,17 @@ services:
MYSQL_ROOT_PASSWORD: 'dXjw127124dJ' MYSQL_ROOT_PASSWORD: 'dXjw127124dJ'
# ports: # ports:
# - "3308:3306" # - "3308:3306"
bapi120:
build:
context: ./
dockerfile: ./BlueWest.Api/Dockerfile
ports:
- 8080:80
environment:
VIRTUAL_HOST: localhost
restart: always
links:
- db:db
container_name: BW1_API