#106 Ajout du mode Repositories Local

This commit is contained in:
Loic Masi
2026-03-26 18:48:41 +01:00
parent c95f77b6e6
commit d65d21ea64
14 changed files with 302 additions and 495 deletions

View File

@@ -7,7 +7,6 @@ namespace Webzine.Repository
using Webzine.EntitiesContext;
using Webzine.Entity;
using Webzine.Entity.Fixtures;
using Webzine.Repository.Fake;
public class DbEntityRepository
{
@@ -18,6 +17,15 @@ namespace Webzine.Repository
this.context = context;
}
/// <summary>
/// Seed la base de donnée à l'aide de SeedDataLocal.
/// </summary>
/// <param name="nbArtistes">Nombre d'artiste.</param>
/// <param name="nbTitres">Nombre de titre.</param>
/// <param name="minStyles">Nombre min de style.</param>
/// <param name="maxStyles">Nombre mac de style.</param>
/// <param name="minCommentairesParTitre">Min commentaire par titre.</param>
/// <param name="maxCommentairesParTitre">Max commentaire par titre</param>
public void SeedBaseDeDonnees(
int nbArtistes = 100,
int nbTitres = 500,
@@ -34,14 +42,16 @@ namespace Webzine.Repository
return;
}
List<Artiste> artistes = ArtisteFactory.CreerListeArtiste(nbArtistes);
List<Style> styles = StyleFactory.CreerListeStyle(minStyles, maxStyles);
List<Artiste> artistes = SeedDataLocal.GenererListeArtiste(nbArtistes);
List<Style> styles = SeedDataLocal.GenererListeStyle(minStyles, maxStyles);
this.context.Artistes.AddRange(artistes);
this.context.Styles.AddRange(styles);
this.context.SaveChanges();
List<Titre> titres = TitreFactory.CreerListeTitre(nbTitres, artistes, styles);
List<string> albums = SeedDataLocal.GenererListeAlbums(3);
List<Titre> titres = SeedDataLocal.GenererListeTitre(nbTitres, artistes, styles, albums);
this.context.Titres.AddRange(titres);
this.context.SaveChanges();
@@ -50,7 +60,7 @@ namespace Webzine.Repository
foreach (Titre titre in titres)
{
commentaires.AddRange(
CommentaireFactory.CreerListeCommentaire(
SeedDataLocal.GenererListeCommentaire(
titre,
minCommentairesParTitre,
maxCommentairesParTitre));

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Text;
using Webzine.Entity;
namespace Webzine.Repository
{
public class InMemoryDataStore
{
public List<Artiste> Artistes { get; set; } = new();
public List<Titre> Titres { get; set; } = new();
public List<Style> Styles { get; set; } = new();
public List<Commentaire> Commentaires { get; set; } = new();
}
}

View File

@@ -15,7 +15,9 @@ namespace Webzine.Repository
public class LocalArtisteRepository : IArtisteRepository
{
private readonly ILogger<LocalArtisteRepository> logger;
private readonly List<Artiste> artistes;
//private readonly List<Artiste> artistes;
private readonly InMemoryDataStore dataStore;
/// <summary>
/// Initializes a new instance of the <see cref="LocalArtisteRepository"/> class.
@@ -23,111 +25,54 @@ namespace Webzine.Repository
/// </summary>
/// <param name="artistes">La liste des artistes à initialiser. Ne peut pas être null.</param>
/// <param name="logger">Le logger à utiliser pour enregistrer les messages de journalisation. Ne peut pas être null.</param>
public LocalArtisteRepository(List<Artiste> artistes, ILogger<LocalArtisteRepository> logger)
public LocalArtisteRepository(InMemoryDataStore dataStore, ILogger<LocalArtisteRepository> logger)
{
this.logger = logger;
this.artistes = artistes;
//this.artistes = artistes;
this.dataStore = dataStore;
}
/// <inheritdoc/>
public void Add(Artiste artiste)
{
try
{
if (this.artistes.Any(a => a.IdArtiste == artiste.IdArtiste))
{
this.logger.LogWarning("Un artiste avec l'ID {Id} existe déjà. L'ajout est ignoré.", artiste.IdArtiste);
return;
}
this.artistes.Add(artiste);
this.logger.LogInformation("Artiste ajouté : {Nom}", artiste.Nom);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'ajout de l'artiste : {Nom}", artiste?.Nom);
throw;
}
throw new NotSupportedException("Mode Local");
}
/// <inheritdoc/>
public void Delete(Artiste artiste)
{
try
{
this.artistes.Remove(artiste);
this.logger.LogInformation("Artiste supprimé : {Nom}", artiste.Nom);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la suppression de l'artiste : {Nom}", artiste.Nom);
throw;
}
throw new NotSupportedException("Mode Local");
}
/// <inheritdoc/>
public Artiste Find(int id)
{
try
var artiste = this.dataStore.Artistes.First(a => a.IdArtiste == id);
if (artiste == null)
{
Artiste artiste = this.artistes.First(a => a.IdArtiste == id);
return artiste;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche de l'artiste avec ID: {Id}", id);
throw;
return new Artiste();
}
return artiste;
}
/// <inheritdoc/>
public Artiste FindByName(string nom)
{
try
{
Artiste artiste = this.artistes.First(a => a.Nom == nom);
return artiste;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche de l'artiste avec le nom: {Nom}", nom);
throw;
}
return this.dataStore.Artistes.First(a => a.Nom == nom);
}
/// <inheritdoc/>
/// La liste retournée est une copie de la liste interne, donc elle ne peut être nulle.
public IEnumerable<Artiste> FindAll()
{
return this.artistes;
return this.dataStore.Artistes;
}
/// <inheritdoc/>
public void Update(Artiste artiste)
{
try
{
var artisteToUpdate = this.artistes.FirstOrDefault(a => a.IdArtiste == artiste.IdArtiste);
if (artisteToUpdate != null)
{
artisteToUpdate.Nom = artiste.Nom;
artisteToUpdate.Biographie = artiste.Biographie;
artisteToUpdate.Titres = artiste.Titres;
this.logger.LogInformation("Artiste {Id} mis à jour avec succès.", artiste.IdArtiste);
}
else
{
this.logger.LogWarning("Mise à jour impossible : l'artiste avec l'ID {Id} n'existe pas.", artiste.IdArtiste);
throw new KeyNotFoundException($"L'artiste {artiste.IdArtiste} est introuvable.");
}
}
catch (Exception ex)
{
this.logger.LogError(ex, "Une erreur est survenue lors de la mise à jour de l'artiste {Id}.", artiste.IdArtiste);
throw;
}
throw new NotSupportedException("Mode Local");
}
}
}

View File

@@ -0,0 +1,43 @@
// <copyright file="LocalCommentaireRepository.cs" company="PlaceholderCompany">
// Copyright (c) PlaceholderCompany. All rights reserved.
// </copyright>
using Webzine.Entity;
using Webzine.Repository.Contracts;
namespace Webzine.Repository
{
public class LocalCommentaireRepository : ICommentaireRepository
{
private readonly InMemoryDataStore dataStore;
public LocalCommentaireRepository(InMemoryDataStore dataStore)
{
this.dataStore = dataStore;
}
/// <inheritdoc/>
public void Add(Commentaire commentaire)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public void Delete(Commentaire commentaire)
{
throw new NotSupportedException();
}
/// <inheritdoc/>
public Commentaire Find(int id)
{
return this.dataStore.Commentaires.Find(c => c.IdCommentaire == id);
}
/// <inheritdoc/>
public IEnumerable<Commentaire> FindAll()
{
return this.dataStore.Commentaires.ToList();
}
}
}

View File

@@ -10,126 +10,48 @@ namespace Webzine.Repository;
public class LocalStyleRepository : IStyleRepository
{
private readonly ILogger<LocalStyleRepository> logger;
private readonly List<Style> styles;
//private readonly List<Style> styles;
private readonly InMemoryDataStore dataStore;
/// <summary>
/// Initializes a new instance of the <see cref="LocalStyleRepository"/> class.
/// </summary>
/// <param name="logger">Le service de journalisation injecté pour suivre les opérations du repository.</param>
/// <param name="styles">La liste de styles à utiliser comme source de données pour le repository.</param>
public LocalStyleRepository(ILogger<LocalStyleRepository> logger, List<Style> styles)
public LocalStyleRepository(ILogger<LocalStyleRepository> logger, InMemoryDataStore dataStore)
{
this.logger = logger;
this.styles = styles;
this.dataStore = dataStore;
this.logger.LogDebug(1, "NLog injecté dans LocalStyleRepository");
}
/// <inheritdoc/>
public void Add(Style style)
{
try
{
this.logger.LogDebug("Ajout du style: {Libelle}", style.Libelle);
this.styles.Add(style);
this.logger.LogDebug("Style ajouté avec succès, ID: {IdStyle}", style.IdStyle);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'ajout du style: {Libelle}", style.Libelle);
throw;
}
throw new NotSupportedException("Mode local");
}
/// <inheritdoc/>
public void Delete(Style style)
{
try
{
this.logger.LogDebug("Suppression du style ID: {IdStyle}", style.IdStyle);
if (!this.styles.Contains(style))
{
this.logger.LogWarning("Le style avec l'identifiant {IdStyle} n'existe pas dans la liste.", style.IdStyle);
}
this.styles.Remove(style);
this.logger.LogDebug("Style supprimé avec succès, ID: {IdStyle}", style.IdStyle);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la suppression du style ID: {IdStyle}", style.IdStyle);
throw;
}
throw new NotSupportedException("Mode local");
}
/// <inheritdoc/>
public Style Find(int id)
{
try
{
this.logger.LogDebug("Recherche du style avec ID: {Id}", id);
if (id <= 0)
{
this.logger.LogWarning("Tentative de recherche d'un style avec un Id invalide: {Id}", id);
return new Style();
}
Style style = this.styles.First(s => s.IdStyle == id);
this.logger.LogDebug("Style trouvé: {Libelle}", style.Libelle);
return style;
}
catch (InvalidOperationException ex)
{
this.logger.LogWarning(ex, "Aucun style trouvé avec l'ID: {Id}", id);
throw;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche du style avec ID: {Id}", id);
throw;
}
return this.dataStore.Styles.Find(s => s.IdStyle == id);
}
/// <inheritdoc/>
public IEnumerable<Style> FindAll()
{
try
{
this.logger.LogDebug("Récupération de tous les styles");
var result = this.styles;
this.logger.LogDebug("{Count} styles récupérés", result.Count);
return result;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la récupération de tous les styles");
throw;
}
return this.dataStore.Styles.ToList();
}
/// <inheritdoc/>
public void Update(Style style)
{
try
{
this.logger.LogDebug("Mise à jour du style ID: {IdStyle}", style.IdStyle);
int index = this.styles.FindIndex(s => s.IdStyle == style.IdStyle);
if (index == -1)
{
this.logger.LogWarning("Aucun style trouvé avec l'identifiant {IdStyle}.", style.IdStyle);
throw new InvalidOperationException($"Aucun style trouvé avec l'identifiant {style.IdStyle}.");
}
this.styles[index] = style;
this.logger.LogDebug("Style mis à jour avec succès, ID: {IdStyle}", style.IdStyle);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la mise à jour du style ID: {IdStyle}", style.IdStyle);
throw;
}
throw new NotSupportedException("Mode local");
}
}

View File

@@ -10,265 +10,90 @@ namespace Webzine.Repository;
public class LocalTitreRepository : ITitreRepository
{
private readonly ILogger<LocalTitreRepository> logger;
private readonly List<Titre> titres;
private readonly InMemoryDataStore dataStore;
/// <summary>
/// Initializes a new instance of the <see cref="LocalTitreRepository"/> class.
/// </summary>
/// <param name="logger">Le service de journalisation injecté pour suivre les opérations du repository.</param>
/// <param name="titres">La liste de titres à utiliser comme source de données pour le repository.</param>
public LocalTitreRepository(ILogger<LocalTitreRepository> logger, List<Titre> titres)
/// <param name="dataStore">La liste de titres à utiliser comme source de données pour le repository.</param>
public LocalTitreRepository(ILogger<LocalTitreRepository> logger, InMemoryDataStore dataStore)
{
this.logger = logger;
this.titres = titres;
this.dataStore = dataStore;
this.logger.LogDebug(1, "NLog injecté dans LocalTitreRepository");
}
/// <inheritdoc/>
public void Add(Titre titre)
{
try
{
this.logger.LogDebug("Ajout du titre: {Libelle}", titre.Libelle);
this.titres.Add(titre);
this.logger.LogDebug("Titre ajouté avec succès, ID: {IdTitre}", titre.IdTitre);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'ajout du titre: {Libelle}", titre.Libelle);
throw;
}
throw new NotSupportedException("Mode local");
}
/// <inheritdoc/>
public int Count()
{
try
{
var count = this.titres.Count;
this.logger.LogDebug("Nombre total de titres: {Count}", count);
return count;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors du comptage des titres");
throw;
}
var count = this.dataStore.Titres.Count();
return count;
}
/// <inheritdoc/>
public void Delete(Titre titre)
{
try
{
this.logger.LogDebug("Suppression du titre ID: {IdTitre}", titre.IdTitre);
if (!this.titres.Contains(titre))
{
this.logger.LogWarning("Le titre avec l'identifiant {IdTitre} n'existe pas dans la liste.", titre.IdTitre);
}
this.titres.Remove(titre);
this.logger.LogDebug("Titre supprimé avec succès, ID: {IdTitre}", titre.IdTitre);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la suppression du titre ID: {IdTitre}", titre.IdTitre);
throw;
}
throw new NotSupportedException("Mode Local");
}
/// <inheritdoc/>
public IEnumerable<Titre> FindTitres(int offset, int limit)
{
try
{
this.logger.LogDebug("Recherche des titres avec offset: {Offset}, limit: {Limit}", offset, limit);
if (offset < 0 || limit <= 0)
{
this.logger.LogWarning("FindTitres appelé avec offset {Offset} ou limit {Limit} invalide.", offset, limit);
return Enumerable.Empty<Titre>();
}
var result = this.titres.Skip(offset).Take(limit).ToList();
this.logger.LogDebug("{Count} titres trouvés", result.Count);
return result;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche des titres avec offset: {Offset}, limit: {Limit}", offset, limit);
throw;
}
return this.dataStore.Titres
.OrderByDescending(t => t.DateCreation)
.Skip(offset)
.Take(limit);
}
/// <inheritdoc/>
public void IncrementNbLectures(Titre titre)
{
try
{
this.logger.LogDebug("Incrémentation du nombre de lectures pour le titre ID: {IdTitre}", titre.IdTitre);
titre.NbLectures++;
this.logger.LogDebug("Nouveau nombre de lectures: {NbLectures}", titre.NbLectures);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'incrémentation des lectures pour le titre ID: {IdTitre}", titre.IdTitre);
throw;
}
titre.NbLectures++;
}
/// <inheritdoc/>
public void IncrementNbLikes(Titre titre)
{
try
{
this.logger.LogDebug("Incrémentation du nombre de likes pour le titre ID: {IdTitre}", titre.IdTitre);
titre.NbLikes++;
this.logger.LogDebug("Nouveau nombre de likes: {NbLikes}", titre.NbLikes);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de l'incrémentation des likes pour le titre ID: {IdTitre}", titre.IdTitre);
throw;
}
titre.NbLikes++;
}
/// <inheritdoc/>
public IEnumerable<Titre> Search(string mot)
{
try
{
this.logger.LogDebug("Recherche de titres avec le mot-clé: {Mot}", mot);
if (string.IsNullOrWhiteSpace(mot))
{
this.logger.LogWarning("Search appelé avec une chaîne vide ou contenant uniquement des espaces.");
return Enumerable.Empty<Titre>();
}
IEnumerable<Titre> list = this.titres
.Where(t => !string.IsNullOrWhiteSpace(t.Libelle)
&& t.Libelle.Contains(mot, StringComparison.OrdinalIgnoreCase))
.OrderBy(t => t.Libelle)
.ToList();
if (!list.Any())
{
this.logger.LogInformation("Aucun titre trouvé correspondant au terme de recherche '{Mot}'.", mot);
}
else
{
this.logger.LogDebug("{Count} titres trouvés pour le mot-clé '{Mot}'", list.Count(), mot);
}
return list;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche des titres avec le mot-clé: {Mot}", mot);
throw;
}
return this.dataStore.Titres
.Where(t => t.Libelle != null && t.Libelle.Contains(mot));
}
/// <inheritdoc/>
public Titre Find(int idTitre)
{
try
{
this.logger.LogDebug("Recherche du titre avec ID: {IdTitre}", idTitre);
Titre titre = this.titres.First(t => t.IdTitre == idTitre);
this.logger.LogDebug("Titre trouvé: {Libelle}", titre.Libelle);
return titre;
}
catch (InvalidOperationException ex)
{
this.logger.LogWarning(ex, "Aucun titre trouvé avec l'ID: {IdTitre}", idTitre);
throw;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche du titre avec ID: {IdTitre}", idTitre);
throw;
}
return this.dataStore.Titres
.First(t => t.IdTitre == idTitre);
}
/// <inheritdoc/>
public IEnumerable<Titre> FindAll()
{
try
{
this.logger.LogDebug("Récupération de tous les titres");
var result = this.titres;
this.logger.LogDebug("{Count} titres récupérés", result.Count);
return result;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la récupération de tous les titres");
throw;
}
return this.dataStore.Titres;
}
/// <inheritdoc/>
public IEnumerable<Titre> SearchByStyle(string libelle)
{
try
{
this.logger.LogDebug("Recherche des titres par style: {Libelle}", libelle);
if (string.IsNullOrWhiteSpace(libelle))
{
this.logger.LogWarning("SearchByStyle appelé avec une chaîne vide ou contenant uniquement des espaces.");
return Enumerable.Empty<Titre>();
}
IEnumerable<Titre> list = this.titres
.Where(t => t.Styles.Any(s => !string.IsNullOrWhiteSpace(s.Libelle)
&& s.Libelle.Contains(libelle, StringComparison.OrdinalIgnoreCase)))
.OrderBy(t => t.Libelle)
.ToList();
if (!list.Any())
{
this.logger.LogInformation("Aucun titre trouvé correspondant au style '{Libelle}'.", libelle);
}
else
{
this.logger.LogDebug("{Count} titres trouvés pour le style '{Libelle}'", list.Count(), libelle);
}
return list;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la recherche des titres par style: {Libelle}", libelle);
throw;
}
return this.dataStore.Titres
.Where(t => t.Styles.Any(s => s.Libelle == libelle));
}
/// <inheritdoc/>
public void Update(Titre titre)
{
try
{
this.logger.LogDebug("Mise à jour du titre ID: {IdTitre}", titre.IdTitre);
int index = this.titres.FindIndex(t => t.IdTitre == titre.IdTitre);
if (index == -1)
{
this.logger.LogWarning("Aucun titre trouvé avec l'identifiant {IdTitre}.", titre.IdTitre);
throw new InvalidOperationException($"Aucun titre trouvé avec l'identifiant {titre.IdTitre}.");
}
this.titres[index] = titre;
this.logger.LogDebug("Titre mis à jour avec succès, ID: {IdTitre}", titre.IdTitre);
}
catch (Exception ex)
{
this.logger.LogError(ex, "Erreur lors de la mise à jour du titre ID: {IdTitre}", titre.IdTitre);
throw;
}
throw new NotSupportedException("Mode local");
}
}