Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/CSharpApp.Api/GlobalUsings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@

global using CSharpApp.Core.Interfaces;
global using CSharpApp.Infrastructure.Configuration;
global using Serilog;
global using Serilog;
global using CSharpApp.Core.Dtos;
global using Microsoft.AspNetCore.Http;
70 changes: 66 additions & 4 deletions src/CSharpApp.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddDefaultConfiguration();
builder.Services.AddHttpConfiguration();
builder.Services.AddDefaultConfiguration(builder.Configuration);
builder.Services.AddHttpConfiguration(builder.Configuration);
builder.Services.AddProblemDetails();
builder.Services.AddApiVersioning();

Expand All @@ -23,12 +23,74 @@

var versionedEndpointRouteBuilder = app.NewVersionedApi();

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/getproducts", async (IProductsService productsService) =>
versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/products", async (IProductsService productsService) =>
{
var products = await productsService.GetProducts();
return products;
return Results.Ok(products);
})
.WithName("GetProducts")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/products/{id}", async (IProductsService productsService, int id, CancellationToken ct) =>
{
var product = await productsService.GetProductById(id, ct);
return product is null ? Results.NotFound() : Results.Ok(product);
})
.WithName("GetProductById")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapPost("api/v{version:apiVersion}/products", async (IProductsService productsService, Product product, HttpContext http, CancellationToken ct) =>
{
if (product == null)
return Results.BadRequest();

// Basic validation
if (string.IsNullOrWhiteSpace(product.Title) || (product.Price.HasValue && product.Price <= 0))
return Results.BadRequest("Invalid product payload");

var created = await productsService.CreateProduct(product, ct);
if (created == null)
return Results.StatusCode(StatusCodes.Status502BadGateway);

var location = $"/api/v1/products/{created.Id}";
return Results.Created(location, created);
})
.WithName("CreateProduct")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/categories", async (ICategoriesService categoriesService) =>
{
var categories = await categoriesService.GetCategories();
return Results.Ok(categories);
})
.WithName("GetCategories")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapGet("api/v{version:apiVersion}/categories/{id}", async (ICategoriesService categoriesService, int id, CancellationToken ct) =>
{
var category = await categoriesService.GetCategoryById(id, ct);
return category is null ? Results.NotFound() : Results.Ok(category);
})
.WithName("GetCategoryById")
.HasApiVersion(1.0);

versionedEndpointRouteBuilder.MapPost("api/v{version:apiVersion}/categories", async (ICategoriesService categoriesService, Category category, HttpContext http, CancellationToken ct) =>
{
if (category == null)
return Results.BadRequest();

// Basic validation
if (string.IsNullOrWhiteSpace(category.Name))
return Results.BadRequest("Invalid category payload");

var created = await categoriesService.CreateCategory(category, ct);
if (created == null)
return Results.StatusCode(StatusCodes.Status502BadGateway);

var location = $"/api/v1/categories/{created.Id}";
return Results.Created(location, created);
})
.WithName("CreateCategory")
.HasApiVersion(1.0);

app.Run();
99 changes: 99 additions & 0 deletions src/CSharpApp.Application/Categories/CategoriesService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
namespace CSharpApp.Application.Categories;

public class CategoriesService : ICategoriesService
{
private readonly HttpClient _httpClient;
private readonly RestApiSettings _restApiSettings;
private readonly ILogger<CategoriesService> _logger;

public CategoriesService(HttpClient httpClient, IOptions<RestApiSettings> restApiSettings,
ILogger<CategoriesService> logger)
{
_httpClient = httpClient;
_restApiSettings = restApiSettings.Value;
_logger = logger;
}

public async Task<IReadOnlyCollection<Category>> GetCategories(CancellationToken cancellationToken = default)
{
try
{
var path = string.IsNullOrWhiteSpace(_restApiSettings.Categories) ? string.Empty : _restApiSettings.Categories;

var response = await _httpClient.GetAsync(path, cancellationToken);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(cancellationToken);

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var res = JsonSerializer.Deserialize<List<Category>>(content, options) ?? new List<Category>();

return res.AsReadOnly();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching categories from remote API");
throw;
}
}

public async Task<Category?> GetCategoryById(int id, CancellationToken cancellationToken = default)
{
try
{
var path = string.IsNullOrWhiteSpace(_restApiSettings.Categories) ? $"{id}" : $"{_restApiSettings.Categories}/{id}";

var response = await _httpClient.GetAsync(path, cancellationToken);

if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}

response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(cancellationToken);

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var category = JsonSerializer.Deserialize<Category>(content, options);

return category;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching category {CategoryId} from remote API", id);
throw;
}
}

public async Task<Category?> CreateCategory(Category category, CancellationToken cancellationToken = default)
{
try
{
if (category is null)
throw new ArgumentNullException(nameof(category));

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var json = JsonSerializer.Serialize(category, options);
using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

var path = string.IsNullOrWhiteSpace(_restApiSettings.Categories) ? string.Empty : _restApiSettings.Categories;

var response = await _httpClient.PostAsync(path, content, cancellationToken);

if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Failed to create category. StatusCode: {StatusCode}", response.StatusCode);
return null;
}

var responseContent = await response.Content.ReadAsStringAsync(cancellationToken);
var created = JsonSerializer.Deserialize<Category>(responseContent, options);

return created ?? category;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating category");
throw;
}
}
}
96 changes: 87 additions & 9 deletions src/CSharpApp.Application/Products/ProductsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,100 @@ public class ProductsService : IProductsService
private readonly RestApiSettings _restApiSettings;
private readonly ILogger<ProductsService> _logger;

public ProductsService(IOptions<RestApiSettings> restApiSettings,
public ProductsService(HttpClient httpClient, IOptions<RestApiSettings> restApiSettings,
ILogger<ProductsService> logger)
{
_httpClient = new HttpClient();
_httpClient = httpClient;
_restApiSettings = restApiSettings.Value;
_logger = logger;
}

public async Task<Product?> GetProductById(int id, CancellationToken cancellationToken = default)
{
try
{
var path = string.IsNullOrWhiteSpace(_restApiSettings.Products) ? $"{id}" : $"{_restApiSettings.Products}/{id}";

var response = await _httpClient.GetAsync(path, cancellationToken);

if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}

response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync(cancellationToken);

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var product = JsonSerializer.Deserialize<Product>(content, options);

return product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching product {ProductId} from remote API", id);
throw;
}
}

public async Task<Product?> CreateProduct(Product product, CancellationToken cancellationToken = default)
{
try
{
// Basic validation
if (product is null)
throw new ArgumentNullException(nameof(product));

var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
var json = JsonSerializer.Serialize(product, options);
using var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");

var path = string.IsNullOrWhiteSpace(_restApiSettings.Products) ? string.Empty : _restApiSettings.Products;

var response = await _httpClient.PostAsync(path, content, cancellationToken);

if (!response.IsSuccessStatusCode)
{
_logger.LogWarning("Failed to create product. StatusCode: {StatusCode}", response.StatusCode);
return null;
}

var responseContent = await response.Content.ReadAsStringAsync(cancellationToken);
var created = JsonSerializer.Deserialize<Product>(responseContent, options);

return created ?? product;
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating product");
throw;
}
}

public async Task<IReadOnlyCollection<Product>> GetProducts()
{
_httpClient.BaseAddress = new Uri(_restApiSettings.BaseUrl!);
var response = await _httpClient.GetAsync(_restApiSettings.Products);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var res = JsonSerializer.Deserialize<List<Product>>(content);

return res.AsReadOnly();
try
{
// If Products path is set, request it; otherwise request root
var path = string.IsNullOrWhiteSpace(_restApiSettings.Products) ? string.Empty : _restApiSettings.Products;

var response = await _httpClient.GetAsync(path);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();

var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};

var res = JsonSerializer.Deserialize<List<Product>>(content, options) ?? new List<Product>();

return res.AsReadOnly();
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching products from remote API");
throw;
}
}
}
1 change: 0 additions & 1 deletion src/CSharpApp.Core/CSharpApp.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

<ItemGroup>
<Folder Include="Dtos\" />
<Folder Include="Interfaces\" />
<Folder Include="Settings\" />
</ItemGroup>

Expand Down
8 changes: 8 additions & 0 deletions src/CSharpApp.Core/Interfaces/ICategoriesService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace CSharpApp.Core.Interfaces;

public interface ICategoriesService
{
Task<IReadOnlyCollection<Category>> GetCategories(CancellationToken cancellationToken = default);
Task<Category?> GetCategoryById(int id, CancellationToken cancellationToken = default);
Task<Category?> CreateCategory(Category category, CancellationToken cancellationToken = default);
}
2 changes: 2 additions & 0 deletions src/CSharpApp.Core/Interfaces/IProductsService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ namespace CSharpApp.Core.Interfaces;
public interface IProductsService
{
Task<IReadOnlyCollection<Product>> GetProducts();
Task<Product?> GetProductById(int id, CancellationToken cancellationToken = default);
Task<Product?> CreateProduct(Product product, CancellationToken cancellationToken = default);
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,12 @@ namespace CSharpApp.Infrastructure.Configuration;

public static class DefaultConfiguration
{
public static IServiceCollection AddDefaultConfiguration(this IServiceCollection services)
public static IServiceCollection AddDefaultConfiguration(this IServiceCollection services, IConfiguration configuration)
{
var serviceProvider = services.BuildServiceProvider();
var configuration = serviceProvider.GetService<IConfiguration>();

services.Configure<RestApiSettings>(configuration!.GetSection(nameof(RestApiSettings)));
// Bind configuration sections to options without building a temporary provider
services.Configure<RestApiSettings>(configuration.GetSection(nameof(RestApiSettings)));
services.Configure<HttpClientSettings>(configuration.GetSection(nameof(HttpClientSettings)));

services.AddSingleton<IProductsService, ProductsService>();

return services;
}
}
}
Loading