feat: ajustes, refinamentos e code cleanup
This commit is contained in:
@@ -10,6 +10,7 @@ services:
|
||||
shop-webapi:
|
||||
image: shop-webapi
|
||||
container_name: shop-webapi
|
||||
restart: always
|
||||
build:
|
||||
context: .
|
||||
dockerfile: src/Shop.PublicApi/Dockerfile
|
||||
|
||||
@@ -61,10 +61,7 @@ public class CustomerCommandHandler :
|
||||
|
||||
// Verificiando se já existe um cliente com o endereço de e-mail.
|
||||
if (await _writeOnlyRepository.ExistsByEmailAsync(email))
|
||||
{
|
||||
// Retorna o resultado com o erro informado:
|
||||
return Result.Error("O endereço de e-mail informado já está sendo utilizado.");
|
||||
}
|
||||
|
||||
// Criando a instancia da entidade cliente.
|
||||
// Ao instanciar será criado o evento: "CustomerCreatedEvent"
|
||||
@@ -102,12 +99,9 @@ public class CustomerCommandHandler :
|
||||
|
||||
// Verificiando se já existe um cliente com o endereço de e-mail.
|
||||
if (await _writeOnlyRepository.ExistsByEmailAsync(newEmail, customerQueryModel.Id))
|
||||
{
|
||||
// Retorna o resultado com o erro informado:
|
||||
return Result.Error("O endereço de e-mail informado já está sendo utilizado.");
|
||||
}
|
||||
|
||||
// Mapeando QueryModel para Entity.
|
||||
// Mapeando QueryModel para Entity (Domain).
|
||||
var customer = _mapper.Map<Domain.Entities.Customer.Customer>(customerQueryModel);
|
||||
customer.ChangeEmail(newEmail);
|
||||
|
||||
@@ -133,7 +127,7 @@ public class CustomerCommandHandler :
|
||||
if (customerQueryModel == null)
|
||||
return Result.NotFound($"Nenhum cliente encontrado pelo Id: {request.Id}");
|
||||
|
||||
// Mapeando QueryModel para Entity.
|
||||
// Mapeando QueryModel para Entity (Domain).
|
||||
var customer = _mapper.Map<Domain.Entities.Customer.Customer>(customerQueryModel);
|
||||
customer.Delete();
|
||||
|
||||
|
||||
@@ -7,15 +7,9 @@ public sealed class ConnectionOptions : BaseOptions
|
||||
{
|
||||
public const string ConfigSectionPath = "ConnectionStrings";
|
||||
|
||||
/// <summary>
|
||||
/// String de conexão com a base de dados relacional.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string ShopConnection { get; private init; }
|
||||
public string SqlConnection { get; private init; }
|
||||
|
||||
/// <summary>
|
||||
/// String de conexão com a base de dados NoSql.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string EventConnection { get; private init; }
|
||||
public string NoSqlConnection { get; private init; }
|
||||
}
|
||||
@@ -18,21 +18,16 @@ public class ReadDbContext
|
||||
private readonly IMongoClient _client;
|
||||
private readonly IMongoDatabase _database;
|
||||
private readonly ILogger<ReadDbContext> _logger;
|
||||
private readonly string _connectionString;
|
||||
|
||||
public ReadDbContext(IOptions<ConnectionOptions> options, ILogger<ReadDbContext> logger)
|
||||
{
|
||||
_connectionString = options.Value.EventConnection;
|
||||
|
||||
_client = new MongoClient(_connectionString);
|
||||
_client = new MongoClient(options.Value.NoSqlConnection);
|
||||
_database = _client.GetDatabase(DatabaseName);
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public IMongoCollection<T> GetCollection<T>() => _database.GetCollection<T>(typeof(T).Name);
|
||||
|
||||
public string GetConnectionString() => _connectionString;
|
||||
|
||||
public async Task CreateCollectionsAsync()
|
||||
{
|
||||
// Obtendo as coleções existentes da base.
|
||||
@@ -47,6 +42,7 @@ public class ReadDbContext
|
||||
if (!collections.Any(name => name == collectionName))
|
||||
{
|
||||
_logger.LogInformation("----- MongoDB: criando a coleção {Name}", collectionName);
|
||||
|
||||
await _database.CreateCollectionAsync(collectionName);
|
||||
}
|
||||
else
|
||||
|
||||
@@ -15,6 +15,7 @@ using Shop.PublicApi.Models;
|
||||
namespace Shop.PublicApi.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[ApiVersion("1.0")]
|
||||
[Route("api/[controller]")]
|
||||
public class CustomersController : ControllerBase
|
||||
{
|
||||
|
||||
@@ -53,7 +53,7 @@ public static class ServicesCollectionExtensions
|
||||
var logger = serviceProvider.GetRequiredService<ILogger<WriteDbContext>>();
|
||||
var connectionOptions = serviceProvider.GetRequiredService<IOptions<ConnectionOptions>>().Value;
|
||||
|
||||
options.UseSqlServer(connectionOptions.ShopConnection, sqlOptions =>
|
||||
options.UseSqlServer(connectionOptions.SqlConnection, sqlOptions =>
|
||||
{
|
||||
sqlOptions.MigrationsAssembly("Shop.PublicApi");
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ var tags = new[] { "database" };
|
||||
builder.Services
|
||||
.AddHealthChecks()
|
||||
.AddDbContextCheck<WriteDbContext>(tags: tags)
|
||||
.AddMongoDb(connectionOptions.EventConnection, tags: tags);
|
||||
.AddMongoDb(connectionOptions.NoSqlConnection, tags: tags);
|
||||
|
||||
// Validando os serviços adicionados no ASP.NET Core DI.
|
||||
builder.Host.UseDefaultServiceProvider((context, options) =>
|
||||
@@ -132,7 +132,7 @@ try
|
||||
|
||||
app.Logger.LogInformation("----- AutoMapper: Mapeamentos são válidos!");
|
||||
|
||||
app.Logger.LogInformation("----- SQL Server: {Connection}", writeDbContext.Database.GetConnectionString());
|
||||
app.Logger.LogInformation("----- SQL Server: {Connection}", connectionOptions.SqlConnection);
|
||||
app.Logger.LogInformation("----- SQL Server: Verificando se existem migrações pendentes...");
|
||||
|
||||
if ((await writeDbContext.Database.GetPendingMigrationsAsync()).Any())
|
||||
@@ -148,7 +148,7 @@ try
|
||||
app.Logger.LogInformation("----- SQL Server: Migrações estão em dia.");
|
||||
}
|
||||
|
||||
app.Logger.LogInformation("----- MongoDB: {Connection}", readDbContext.GetConnectionString());
|
||||
app.Logger.LogInformation("----- MongoDB: {Connection}", connectionOptions.NoSqlConnection);
|
||||
app.Logger.LogInformation("----- MongoDB: criando as coleções...");
|
||||
|
||||
await readDbContext.CreateCollectionsAsync();
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
<DockerTargetOS>Linux</DockerTargetOS>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<IncludeOpenAPIAnalyzers>true</IncludeOpenAPIAnalyzers>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"ShopConnection": "Server=127.0.0.1;Integrated Security=true;Initial Catalog=ShopContext;User Id=sa;Password=Sxc56Nu9V;Trusted_Connection=false;MultipleActiveResultSets=true;Encrypt=True;TrustServerCertificate=True;",
|
||||
"EventConnection": "mongodb://localhost:27017"
|
||||
"SqlConnection": "Server=127.0.0.1;Integrated Security=true;Initial Catalog=ShopContext;User Id=sa;Password=Sxc56Nu9V;Trusted_Connection=false;MultipleActiveResultSets=true;Encrypt=True;TrustServerCertificate=True;",
|
||||
"NoSqlConnection": "mongodb://localhost:27017"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
}
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"ShopConnection": "Server=sqlserver;Integrated Security=true;Initial Catalog=ShopContext;User Id=sa;Password=Sxc56Nu9V;Trusted_Connection=false;MultipleActiveResultSets=true;Encrypt=True;TrustServerCertificate=True;",
|
||||
"EventConnection": "mongodb://mongoserver"
|
||||
"SqlConnection": "Server=sqlserver;Integrated Security=true;Initial Catalog=ShopContext;User Id=sa;Password=Sxc56Nu9V;Trusted_Connection=false;MultipleActiveResultSets=true;Encrypt=True;TrustServerCertificate=True;",
|
||||
"NoSqlConnection": "mongodb://mongoserver"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user