Run code clean and fix messages (#45)
All checks were successful
Game Ideas deploy / build-test-deploy (push) Successful in 1m13s

Reviewed-on: #45
This commit was merged in pull request #45.
This commit is contained in:
2025-05-07 01:28:37 +02:00
parent b58ffe10e0
commit 58da2e6843
38 changed files with 150 additions and 155 deletions

View File

@@ -6,7 +6,7 @@ namespace GameIdeas.WebAPI.Context;
public class GameIdeasContext : IdentityDbContext<User>
{
public GameIdeasContext(DbContextOptions<GameIdeasContext> option)
public GameIdeasContext(DbContextOptions<GameIdeasContext> option)
: base(option)
{
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
@@ -25,14 +25,16 @@ public class GameIdeasContext : IdentityDbContext<User>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Developer>(entity => {
modelBuilder.Entity<Developer>(entity =>
{
entity.ToTable("Developer");
entity.HasIndex(e => e.Name)
.IsUnique();
});
modelBuilder.Entity<Platform>(entity => {
modelBuilder.Entity<Platform>(entity =>
{
entity.ToTable("Platform");
entity.HasIndex(e => e.Label)
@@ -41,18 +43,18 @@ public class GameIdeasContext : IdentityDbContext<User>
modelBuilder.Entity<Property>(entity =>
{
entity.ToTable("Property");
entity.ToTable("Property");
entity.HasIndex(e => e.Label)
.IsUnique();
});
modelBuilder.Entity<Publisher>(entity =>
{
entity.ToTable("Publisher");
modelBuilder.Entity<Publisher>(entity =>
{
entity.ToTable("Publisher");
entity.HasIndex(e => e.Name)
.IsUnique();
.IsUnique();
});
modelBuilder.Entity<Tag>(entity =>

View File

@@ -11,7 +11,7 @@ namespace GameIdeas.WebAPI.Controllers;
public class GameController(
IGameReadService gameReadService,
IGameWriteService gameWriteService,
IGameWriteService gameWriteService,
ILoggerFactory loggerFactory) : Controller
{
private readonly ILogger<GameController> logger = loggerFactory.CreateLogger<GameController>();
@@ -73,7 +73,7 @@ public class GameController(
{
logger.LogError(e, "Internal error while update game");
return StatusCode(500, e.Message);
}
}
}
[Authorize(Roles = GlobalConstants.ADMIN_MEMBER)]

View File

@@ -5,32 +5,32 @@ namespace GameIdeas.WebAPI.Controllers;
[ApiController]
[Route("api/[controller]")]
public class TranslationsController (ILogger<TranslationsController> Logger) : ControllerBase
public class TranslationsController(ILogger<TranslationsController> Logger) : ControllerBase
{
[HttpGet]
public async Task<IActionResult> GetTranslations()
{
var dictionary = new Dictionary<string, string>();
public async Task<IActionResult> GetTranslations()
{
var dictionary = new Dictionary<string, string>();
try
{
var filesDirectory = Path.Combine(
Directory.GetCurrentDirectory(),
"Files");
var translationFiles = Directory.GetFiles(filesDirectory, "*.json");
foreach (var file in translationFiles)
{
var name = file.Split('.');
var culture = name[^2];
var content = await System.IO.File.ReadAllTextAsync(file);
dictionary.Add(culture, content);
}
}
catch(Exception ex)
{
Logger.LogError(ex, "Internal translations error");
}
try
{
var filesDirectory = Path.Combine(
Directory.GetCurrentDirectory(),
"Files");
var translationFiles = Directory.GetFiles(filesDirectory, "*.json");
foreach (var file in translationFiles)
{
var name = file.Split('.');
var culture = name[^2];
var content = await System.IO.File.ReadAllTextAsync(file);
dictionary.Add(culture, content);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Internal translations error");
}
return Ok(dictionary);
}
return Ok(dictionary);
}
}

View File

@@ -19,22 +19,22 @@ public class UserController(
[HttpPost("Login")]
public async Task<ActionResult<TokenDto>> Login([FromBody] UserDto model)
{
try
{
try
{
return Ok(await userReadService.Login(model));
}
catch (UserInvalidException e)
{
}
catch (UserInvalidException e)
{
logger.LogInformation(e, "Missing informations for authentication");
return StatusCode(406, e.Message);
}
catch (UserUnauthorizedException e)
catch (UserUnauthorizedException e)
{
logger.LogWarning(e, "Authentication invalid with there informations");
return Unauthorized(e.Message);
}
catch (Exception e)
{
{
logger.LogError(e, "Internal error while search games");
return StatusCode(500, e.Message);
}

View File

@@ -1,3 +1,3 @@
namespace GameIdeas.WebAPI.Exceptions;
public class UserInvalidException (string message) : Exception(message);
public class UserInvalidException(string message) : Exception(message);

View File

@@ -1,5 +1,4 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable

View File

@@ -54,7 +54,7 @@ namespace GameIdeas.WebAPI.Migrations
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql(@$"DELETE FROM ""AspNetUserRoles"" WHERE ""UserId"" = '{GlobalConstants.ADMINISTRATOR_USER_ID.ToString()}' AND ""RoleId"" = '{GlobalConstants.ADMINISTRATOR_ID.ToString()}'");
migrationBuilder.Sql(@$"DELETE FROM ""AspNetUserRoles"" WHERE ""UserId"" = '{GlobalConstants.ADMINISTRATOR_USER_ID}' AND ""RoleId"" = '{GlobalConstants.ADMINISTRATOR_ID}'");
migrationBuilder.DeleteData("AspNetUsers", "Id", GlobalConstants.ADMINISTRATOR_USER_ID.ToString());
migrationBuilder.DeleteData("AspNetRoles", "Id", GlobalConstants.ADMINISTRATOR_ID.ToString());
migrationBuilder.DeleteData("AspNetRoles", "Id", GlobalConstants.MEMBER_ID.ToString());

View File

@@ -39,7 +39,7 @@ services.AddIdentity<User, IdentityRole>()
.AddDefaultTokenProviders();
var jwtKey = Environment.GetEnvironmentVariable("JWT_KEY")
?? throw new ArgumentNullException(message: "Invalid key for JWT token", null);
?? throw new ArgumentNullException(message: "Invalid key for JWT token", null);
services.AddAuthentication(options =>
{

View File

@@ -60,7 +60,7 @@ public class GameReadService(GameIdeasContext context, IMapper mapper, ICategory
Expression propertyAccess = Expression.PropertyOrField(param, filter.SortPropertyName);
var converted = Expression.Convert(propertyAccess, typeof(object));
var lambda = Expression.Lambda<Func<Game, object>>(converted, param);
if (filter.SortType == Shared.Enum.SortType.Ascending)
{
query = Queryable.OrderBy(query, lambda);
@@ -116,7 +116,7 @@ public class GameReadService(GameIdeasContext context, IMapper mapper, ICategory
if (filter.ReleaseYears != null)
{
query = query.Where(game => game.ReleaseDate != null &&
query = query.Where(game => game.ReleaseDate != null &&
filter.ReleaseYears.Contains(game.ReleaseDate.Value.Year));
}
}
@@ -130,15 +130,14 @@ public class GameReadService(GameIdeasContext context, IMapper mapper, ICategory
.Select(k => k.Trim())
.ToArray() ?? [];
games = games
games = [.. games
.Where(game => keywords.All(
kw => game.Title.Contains(kw, StringComparison.OrdinalIgnoreCase)
))
.OrderBy(game => keywords.Min(kw =>
game.Title.IndexOf(kw, StringComparison.OrdinalIgnoreCase)
))
.ThenBy(game => game.Title.Length)
.ToList();
.ThenBy(game => game.Title.Length)];
return;
}
@@ -147,10 +146,9 @@ public class GameReadService(GameIdeasContext context, IMapper mapper, ICategory
{
var storageSpaces = categoryService.GetStorageSpaces().Where(stor => filter.StorageSpaces.Contains(stor.Id));
games = games
games = [.. games
.Where(game => storageSpaces.Any(stor =>
(stor.MinSize ?? int.MinValue) <= game.StorageSpace && (stor.MaxSize ?? int.MaxValue) > game.StorageSpace))
.ToList();
(stor.MinSize ?? int.MinValue) <= game.StorageSpace && (stor.MaxSize ?? int.MaxValue) > game.StorageSpace))];
}
}
}

View File

@@ -91,15 +91,14 @@ public class UserReadService(
.Select(k => k.Trim())
.ToArray() ?? [];
users = users
users = [.. users
.Where(user => keywords.All(
kw => user.UserName?.Contains(kw, StringComparison.OrdinalIgnoreCase) ?? true
))
.OrderBy(user => keywords.Min(kw =>
user.UserName?.IndexOf(kw, StringComparison.OrdinalIgnoreCase)
))
.ThenBy(user => user.UserName?.Length)
.ToList();
.ThenBy(user => user.UserName?.Length)];
}
}

View File

@@ -1,5 +1,4 @@
using AutoMapper;
using GameIdeas.Resources;
using GameIdeas.Resources;
using GameIdeas.Shared.Dto;
using GameIdeas.Shared.Model;
using GameIdeas.WebAPI.Exceptions;
@@ -12,8 +11,8 @@ public class UserWriteService(
{
public async Task<string> CreateUser(UserDto user)
{
if (user.Username == null ||
user.Password == null ||
if (user.Username == null ||
user.Password == null ||
user.Role == null)
{
throw new UserInvalidException(ResourcesKey.MissingField);
@@ -75,7 +74,7 @@ public class UserWriteService(
{
var roles = await userManager.GetRolesAsync(userToUpdate);
await userManager.RemoveFromRolesAsync(userToUpdate, roles);
await userManager.AddToRoleAsync(userToUpdate, user.Role.Name);
await userManager.AddToRoleAsync(userToUpdate, user.Role.Name);
}
return userToUpdate.Id;