Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Back end Tech Test - Jordan #680

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
18 changes: 18 additions & 0 deletions jobs/Backend/Task/API/API.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="7.2.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Application\Application.csproj" />
<ProjectReference Include="..\Infrastructure\Infrastructure.csproj" />
</ItemGroup>

</Project>
18 changes: 18 additions & 0 deletions jobs/Backend/Task/API/Controllers/ControllerWithMediatR.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace Api.Controllers;

public abstract class ControllerWithMediatR : ControllerBase
{
private readonly ISender _sender;

protected ControllerWithMediatR(ISender sender)
{
_sender = sender;
}

protected Task<TResponse> Send<TResponse>(
IRequest<TResponse> request,
CancellationToken cancellationToken) => _sender.Send(request, cancellationToken);
}
35 changes: 35 additions & 0 deletions jobs/Backend/Task/API/Controllers/ExchangeRatesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Api.Controllers;
using Application.Extensions;
using Application.UseCases.ExchangeRates;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace API.Controllers;

[ApiController]
[Route("api/v1/{language}/")]
public class ExchangeRatesController(ISender sender) : ControllerWithMediatR(sender)
{
[HttpGet]
[Route("exchangeRates")]
public async Task<IActionResult> GetDailyAsync(
[FromRoute] string language,
[FromQuery] string currencyCode,
CancellationToken token)
{
var result = await Send(new GetDailyExchangeRateRequest().GetQuery(currencyCode, language), token);
return result.IsSuccess ? Ok(result.Value) : result.GetErrorResponse();
}

[HttpGet]
[Route("exchangeRate")]
public async Task<IActionResult> GetExchangeRateAsync(
[FromRoute] string language,
[FromQuery] string fromCurrency,
[FromQuery] string toCurrency,
CancellationToken token)
{
var result = await Send(new GetExchangeRateRequest().GetQuery(language, fromCurrency, toCurrency), token);
return result.IsSuccess ? Ok(result.Value) : result.GetErrorResponse();
}
}
34 changes: 34 additions & 0 deletions jobs/Backend/Task/API/Handlers/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;

namespace Api.Handlers;

public class GlobalExceptionHandler : IExceptionHandler
{
private readonly ILogger<GlobalExceptionHandler> _logger;

public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}

public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken)
{
_logger.LogError(exception, "Exception ocurred: {Message}", exception.Message);

var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Title = "Server Error",
Type = "https://datatracker.ietf.org/doc/html/rfc7231#section-6.6.1"
};

httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;

await httpContext.Response.WriteAsJsonAsync(problemDetails, cancellationToken);
return true;
}
}
37 changes: 37 additions & 0 deletions jobs/Backend/Task/API/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Api.Handlers;
using Application.Regstration;
using Infrastructure.Registration;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseExceptionHandler();

app.MapControllers();

app.Run();
38 changes: 38 additions & 0 deletions jobs/Backend/Task/API/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:31464",
"sslPort": 44349
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5244",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7065;http://localhost:5244",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
8 changes: 8 additions & 0 deletions jobs/Backend/Task/API/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
15 changes: 15 additions & 0 deletions jobs/Backend/Task/API/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"CNBSettings": {
"BaseURL": "https://api.cnb.cz/",
"ExchangeRateURL": "cnbapi/exrates/daily",
"RefreshTimeHour": 2,
"RefreshTimeMinute": 30
}
}
28 changes: 28 additions & 0 deletions jobs/Backend/Task/Application.Tests/Application.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="xunit" Version="2.5.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.5.3" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Application\Application.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using Application.UseCases.ExchangeRates;
using Domain.Abstractions;
using Domain.Abstractions.Data;
using Domain.Errors;
using Domain.Models;
using Microsoft.Extensions.Logging;
using Moq;

namespace Application.Tests;

public class GetDailyExchangeRateQueryHandlerTests
{
private readonly Mock<ILogger<GetDailyExchangeRateQueryHandler>> _mockLogger;
private readonly Mock<IAvailableCurrencies> _mockCurrencyData;
private readonly Mock<IExchangeRateProvider> _mockExchangeRateProvider;
private readonly GetDailyExchangeRateQueryHandler _handler;

public GetDailyExchangeRateQueryHandlerTests()
{
_mockLogger = new Mock<ILogger<GetDailyExchangeRateQueryHandler>>();
_mockCurrencyData = new Mock<IAvailableCurrencies>();
_mockExchangeRateProvider = new Mock<IExchangeRateProvider>();

_handler = new GetDailyExchangeRateQueryHandler(
_mockLogger.Object,
_mockCurrencyData.Object,
_mockExchangeRateProvider.Object);
}

[Fact]
public async Task Handle_ShouldReturnFailure_WhenCurrencyNotFound()
{
// Arrange
var query = new GetDailyExchangeRateQuery("XYZ", "en");
_mockCurrencyData
.Setup(m => m.GetCurrencyWithCode("XYZ"))
.Returns((Currency)null);

// Act
var result = await _handler.Handle(query, CancellationToken.None);

// Assert
Assert.False(result.IsSuccess);
Assert.Single(result.Errors);
Assert.IsType<CurrencyNotFound>(result.Errors[0]);
_mockLogger.Verify(
x => x.Log(
It.IsAny<LogLevel>(),
It.IsAny<EventId>(),
It.IsAny<It.IsAnyType>(),
It.IsAny<Exception>(),
(Func<It.IsAnyType, Exception, string>)It.IsAny<object>()),
Times.Once);
}

[Fact]
public async Task Handle_ShouldReturnSuccess_WhenCurrencyIsFound()
{
// Arrange
var query = new GetDailyExchangeRateQuery("USD", "en");
var currency = new Currency("USD");
var exchangeRates = new List<ExchangeRate>
{
new ExchangeRate(currency, new Currency("EUR"), 1.2m)
};

_mockCurrencyData
.Setup(m => m.GetCurrencyWithCode("USD"))
.Returns(currency);

_mockExchangeRateProvider
.Setup(m => m.GetDailyExchangeRates(currency, "en"))
.ReturnsAsync(exchangeRates);

// Act
var result = await _handler.Handle(query, CancellationToken.None);

// Assert
Assert.True(result.IsSuccess);
Assert.NotNull(result.Value);
Assert.Equal(exchangeRates, result.Value.ExchangeRates);
}
}
Loading