Skip to content

Commit

Permalink
modernized models
Browse files Browse the repository at this point in the history
  • Loading branch information
ClaudiuHBann committed Aug 30, 2024
1 parent dd48b67 commit 17e7341
Show file tree
Hide file tree
Showing 26 changed files with 112 additions and 140 deletions.
21 changes: 13 additions & 8 deletions API/Controllers/BaseController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using Microsoft.AspNetCore.Mvc;

using Shared.Responses;
using Shared.Exceptions;

namespace API.Controllers
{
Expand All @@ -11,16 +12,20 @@ public abstract class BaseController : ControllerBase
{
protected OkObjectResult MakeOk(object data) => Ok(data);

protected BadRequestObjectResult MakeBadRequest(string message) =>
BadRequest(new ErrorResponse(HttpStatusCode.BadRequest, message));
protected BadRequestObjectResult MakeBadRequest(string message) => BadRequest(new ErrorResponse() {
Code = HttpStatusCode.BadRequest, Message = message, TypeException = BaseException.EType.Unknown
});

protected UnauthorizedObjectResult MakeUnauthorized(string message) =>
Unauthorized(new ErrorResponse(HttpStatusCode.Unauthorized, message));
protected UnauthorizedObjectResult MakeUnauthorized(string message) => Unauthorized(new ErrorResponse() {
Code = HttpStatusCode.Unauthorized, Message = message, TypeException = BaseException.EType.Unknown
});

protected NotFoundObjectResult MakeNotFound(string message) => NotFound(new ErrorResponse(HttpStatusCode.NotFound,
message));
protected NotFoundObjectResult MakeNotFound(string message) => NotFound(new ErrorResponse() {
Code = HttpStatusCode.NotFound, Message = message, TypeException = BaseException.EType.Unknown
});

protected ObjectResult MakeInternalAPIError(string message) => new(new ErrorResponse(
HttpStatusCode.InternalServerError, message)) { StatusCode = StatusCodes.Status500InternalServerError };
protected ObjectResult MakeInternalAPIError(string message) => new(new ErrorResponse() {
Code = HttpStatusCode.InternalServerError, Message = message, TypeException = BaseException.EType.Unknown
}) { StatusCode = StatusCodes.Status500InternalServerError };
}
}
3 changes: 2 additions & 1 deletion API/Middlewares/GlobalExceptionHandlerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
_logger.LogError($"Exception: {exception.Message}");

ErrorResponse error = new(HttpStatusCode.InternalServerError, exception.Message);
ErrorResponse error = new() { Code = HttpStatusCode.InternalServerError, Message = exception.Message,
TypeException = BaseException.EType.Unknown };
context.Response.StatusCode = (int)error.Code;
await context.Response.WriteAsJsonAsync(error);
}
Expand Down
42 changes: 28 additions & 14 deletions API/Services/BaseDbService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,23 +69,27 @@ private enum EAction
private async Task<Entity> CRUD<Entity>(Entity entity, EAction action)
where Entity : BaseEntity
{
var methodValidation =
this.Invoke<Task>($"{action}Validate", [entity]) ??
throw new DatabaseException(new(HttpStatusCode.InternalServerError,
$"Failed {action.ToString().ToLower()} validation for {entity}!"));
var methodValidation = this.Invoke<Task>($"{action}Validate", [entity]) ??
throw new DatabaseException(
new() { Code = HttpStatusCode.InternalServerError,
Message = $"Failed {action.ToString().ToLower()} validation for {entity}!",
TypeException = BaseException.EType.Database });
await methodValidation;

var methodCRUD = this.Invoke<Task<Entity>>($"{action}Ex", [entity]) ??
throw new DatabaseException(new(HttpStatusCode.InternalServerError,
$"Failed to {action.ToString().ToLower()} {entity}!"));
var methodCRUD =
this.Invoke<Task<Entity>>($"{action}Ex", [entity]) ??
throw new DatabaseException(new() { Code = HttpStatusCode.InternalServerError,
Message = $"Failed to {action.ToString().ToLower()} {entity}!",
TypeException = BaseException.EType.Database });
return await methodCRUD;
}

private DbSet<Entity> GetDbSet<Entity>()
where Entity : BaseEntity
{
var exception = new DatabaseException(
new(HttpStatusCode.InternalServerError, $"Failed to get the database set for {typeof(Entity)}."));
var exception = new DatabaseException(new() { Code = HttpStatusCode.InternalServerError,
Message = $"Failed to get the database set for {typeof(Entity)}.",
TypeException = BaseException.EType.Database });

foreach (var property in _context.GetType().GetProperties())
{
Expand All @@ -106,7 +110,9 @@ protected async Task<Entity> CreateEx<Entity>(Entity entity)
await GetDbSet<Entity>().AddAsync(entity);
return await _context.SaveChangesAsync() > 0
? entity
: throw new DatabaseException(new(HttpStatusCode.BadRequest, $"Failed to create {entity}!"));
: throw new DatabaseException(new() { Code = HttpStatusCode.BadRequest,
Message = $"Failed to create {entity}!",
TypeException = BaseException.EType.Database });
}

protected async Task<Entity> ReadEx<Entity>(Entity entity)
Expand All @@ -116,7 +122,9 @@ protected async Task<Entity> ReadEx<Entity>(Entity entity)
var propertyIDValue = propertyID?.GetValue(entity);

return await _context.FindAsync(typeof(Entity), propertyIDValue) as Entity ??
throw new DatabaseException(new(HttpStatusCode.NotFound, $"The {typeof(Entity)} could not be found!"));
throw new DatabaseException(new() { Code = HttpStatusCode.NotFound,
Message = $"The {typeof(Entity)} could not be found!",
TypeException = BaseException.EType.Database });
}

protected async Task<Entity> UpdateEx<Entity>(Entity entity)
Expand Down Expand Up @@ -146,7 +154,9 @@ protected async Task<Entity> UpdateEx<Entity>(Entity entity)

var updated = await _context.SaveChangesAsync() > 0 || equalCount > 0;
return updated ? entityUpdated
: throw new DatabaseException(new(HttpStatusCode.BadRequest, $"Failed to update the {entity}!"));
: throw new DatabaseException(new() { Code = HttpStatusCode.BadRequest,
Message = $"Failed to update the {entity}!",
TypeException = BaseException.EType.Database });
}

protected async Task Exists<Entity>(Entity entity, bool throwIfExists = false)
Expand All @@ -159,11 +169,15 @@ protected async Task Exists<Entity>(Entity entity, bool throwIfExists = false)
var exists = await _context.FindAsync(typeof(Entity), propertyIDValue) != null;
if (exists && throwIfExists)
{
throw new DatabaseException(new(HttpStatusCode.NotFound, $"The {typeof(Entity)} already exists!"));
throw new DatabaseException(new() { Code = HttpStatusCode.NotFound,
Message = $"The {typeof(Entity)} already exists!",
TypeException = BaseException.EType.Database });
}
else if (!exists && !throwIfExists)
{
throw new DatabaseException(new(HttpStatusCode.NotFound, $"The {typeof(Entity)} could not be found!"));
throw new DatabaseException(new() { Code = HttpStatusCode.NotFound,
Message = $"The {typeof(Entity)} could not be found!",
TypeException = BaseException.EType.Database });
}
}
}
Expand Down
9 changes: 2 additions & 7 deletions API/Services/BaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,11 @@

namespace API.Services
{
public abstract class BaseService<Request, Response> : BaseDbService<Request, Response>
public abstract class BaseService<Request, Response>(UCContext context) : BaseDbService<Request, Response>(context)
where Request : BaseRequest
where Response : BaseResponse
{
private readonly UCContext _context;

protected BaseService(UCContext context) : base(context)
{
_context = context;
}
private readonly UCContext _context = context;

public abstract bool IsConverter();
public abstract string GetServiceName();
Expand Down
2 changes: 1 addition & 1 deletion API/Services/CommonService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public CommonService(IServiceProvider provider, UCContext context) : base(contex
protected override Task<CommonResponse> ConvertInternal(CommonRequest request) =>
throw new InvalidOperationException();

public async Task<CommonResponse> FromToAll() => new(await FindFromToAll());
public async Task<CommonResponse> FromToAll() => new() { FromToAll = await FindFromToAll() };

public List<IService> FindAllServices()
{
Expand Down
6 changes: 4 additions & 2 deletions API/Services/CurrencyService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public CurrencyService(UCContext context) : base(context)
public override async Task<FromToResponse> FromTo()
{
await FindRates();
return new(_fromTo, _defaultFrom, _defaultTo);
return new() { FromTo = _fromTo, DefaultFrom = _defaultFrom, DefaultTo = _defaultTo };
}

protected override async Task<CurrencyResponse> ConvertInternal(CurrencyRequest request)
Expand All @@ -44,7 +44,9 @@ protected override async Task<CurrencyResponse> ConvertInternal(CurrencyRequest
try
{
// divide by from first because the currency is in EUR by default
return new(request.Money.Select(money => money / _rates[request.From] * _rates[request.To]).ToList());
return new() {
Money = request.Money.Select(money => money / _rates[request.From] * _rates[request.To]).ToList()
};
}
catch (OverflowException)
{
Expand Down
32 changes: 14 additions & 18 deletions API/Services/LinkZipService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,19 @@

namespace API.Services
{
public class LinkZipService : BaseService<LinkZipRequest, LinkZipResponse>
public class LinkZipService
(UCContext context, RadixService radix, IAppCache cache, LinkValidator validator)
: BaseService<LinkZipRequest, LinkZipResponse>(context)
{
private readonly UCContext _context;
private readonly RadixService _radix;
private readonly IAppCache _cache;
private readonly LinkValidator _validator;
private readonly UCContext _context = context;
private readonly RadixService _radix = radix;
private readonly IAppCache _cache = cache;
private readonly LinkValidator _validator = validator;

private const string _defaultFrom = "Longifier";
private const string _defaultTo = "Shortifier";
private static readonly string[] _fromTo = [_defaultTo, _defaultFrom];

public LinkZipService(UCContext context, RadixService radix, IAppCache cache, LinkValidator validator)
: base(context)
{
_context = context;
_radix = radix;
_cache = cache;
_validator = validator;
}

public override bool IsConverter() => true;

public override string GetServiceName() => "LinkZip";
Expand All @@ -46,9 +39,8 @@ private string GetPrefix()
#endif
}

public override async Task<FromToResponse> FromTo() => await Task.FromResult(new FromToResponse([.._fromTo],
_defaultFrom,
_defaultTo));
public override async Task<FromToResponse> FromTo() => await Task.FromResult(
new FromToResponse() { FromTo = [.._fromTo], DefaultFrom = _defaultFrom, DefaultTo = _defaultTo });

protected override async Task ConvertValidate(LinkZipRequest request)
{
Expand Down Expand Up @@ -81,10 +73,12 @@ protected override async Task<LinkZipResponse> ConvertInternal(LinkZipRequest re
urls.Add(await this.Invoke<Task<string>>($"{request.From[0]}To{request.To[0]}", [url])!);
}

return new(urls);
return new() { URLs = urls };
}

#pragma warning disable IDE0051 // Remove unused private members
private async Task<string> SToL(string url)
#pragma warning restore IDE0051 // Remove unused private members
{
var link = await _cache.GetAsync<string>(url);
if (link != null)
Expand All @@ -99,7 +93,9 @@ private async Task<string> SToL(string url)
return entity.Url;
}

#pragma warning disable IDE0051 // Remove unused private members
private async Task<string> LToS(string urlLong)
#pragma warning restore IDE0051 // Remove unused private members
{
var urlShort = await _cache.GetAsync<string>(urlLong);
if (urlShort != null)
Expand Down
15 changes: 6 additions & 9 deletions API/Services/RadixService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

namespace API.Services
{
public class RadixService : BaseService<RadixRequest, RadixResponse>
public class RadixService
(UCContext context) : BaseService<RadixRequest, RadixResponse>(context)
{
private const string Bases = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

Expand All @@ -20,17 +21,12 @@ public class RadixService : BaseService<RadixRequest, RadixResponse>
private const string _defaultFrom = "10";
private const string _defaultTo = "2";

public RadixService(UCContext context) : base(context)
{
}

public override bool IsConverter() => true;

public override string GetServiceName() => "Radix";

public override async Task<FromToResponse> FromTo() => await Task.FromResult(new FromToResponse(_fromTo,
_defaultFrom,
_defaultTo));
public override async Task<FromToResponse> FromTo() => await Task.FromResult(
new FromToResponse() { FromTo = _fromTo, DefaultFrom = _defaultFrom, DefaultTo = _defaultTo });

protected override async Task ConvertValidate(RadixRequest request)
{
Expand All @@ -51,7 +47,8 @@ protected override async Task<RadixResponse> ConvertInternal(RadixRequest reques
var from = ulong.Parse(request.From);
var to = ulong.Parse(request.To);

RadixResponse response = new(request.Numbers.Select(number => ToBase(number, from, to)).ToList());
RadixResponse response =
new() { Numbers = request.Numbers.Select(number => ToBase(number, from, to)).ToList() };
return await Task.FromResult(response);
}

Expand Down
2 changes: 1 addition & 1 deletion API/Services/RankService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public async Task<RankResponse> Converters(RankRequest request)
.Select(rank => rank.Converter)
.ToListAsync();

return new RankResponse(converters);
return new RankResponse() { Converters = converters };
}
}
}
8 changes: 4 additions & 4 deletions API/Services/TemperatureService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,17 @@ public TemperatureService(UCContext context) : base(context)

public override string GetServiceName() => "Temperature";

public override async Task<FromToResponse> FromTo() => await Task.FromResult(new FromToResponse(_fromTo,
_defaultFrom,
_defaultTo));
public override async Task<FromToResponse> FromTo() => await Task.FromResult(new FromToResponse() {
FromTo = _fromTo, DefaultFrom = _defaultFrom, DefaultTo = _defaultTo
});

protected override async Task<TemperatureResponse> ConvertInternal(TemperatureRequest request)
{
var algorithm = FindDirectConversion(request);
try
{
TemperatureResponse response =
new(request.Temperatures.Select(temperature => algorithm(temperature)).ToList());
new() { Temperatures = request.Temperatures.Select(temperature => algorithm(temperature)).ToList() };
return await Task.FromResult(response);
}
catch (OverflowException)
Expand Down
14 changes: 3 additions & 11 deletions Shared/Entities/LinkEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
namespace Shared.Entities
{
[Table("link")]
public class LinkEntity : BaseEntity
public class LinkEntity
(string url = "") : BaseEntity
{
[Key]
[Required]
Expand All @@ -16,15 +17,6 @@ public class LinkEntity : BaseEntity
[Column("url")]
public string Url {
get; set;
} = "";

public LinkEntity()
{
}

public LinkEntity(string url)
{
Url = url;
}
} = url;
}
}
10 changes: 3 additions & 7 deletions Shared/Entities/RankEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
namespace Shared.Entities
{
[Table("rank")]
public class RankEntity : BaseEntity
public class RankEntity
(string converter) : BaseEntity
{
[Key]
[Required]
Expand All @@ -16,17 +17,12 @@ public class RankEntity : BaseEntity
[Column("converter")]
public string Converter {
get; set;
} = "";
} = converter;

[Required]
[Column("conversions")]
public long Conversions {
get; set;
} = 0;

public RankEntity(string converter)
{
Converter = converter;
}
}
}
9 changes: 0 additions & 9 deletions Shared/Exceptions/BaseException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,15 +20,6 @@ protected BaseException(EType type, ErrorResponse error) : base(error.Message)
Type = type;

Error = error;
Error.TypeException = type;
}

protected BaseException(EType type, ErrorResponse error, Exception inner) : base(error.Message, inner)
{
Type = type;

Error = error;
Error.TypeException = type;
}
}
}
Loading

0 comments on commit 17e7341

Please sign in to comment.