From 76de6eccbb8f7f10f39154f180c869378bda7fe2 Mon Sep 17 00:00:00 2001 From: "nathan.boileau" Date: Sun, 26 Mar 2023 22:31:45 +0200 Subject: [PATCH] Finish link between API and DB :white_check_mark: --- Sources/EFLol/DBDataManager/EFDataManager.cs | 253 ++++++++++-------- .../DBDataManager/ExtensionsDataManager.cs | 71 +++++ .../apiLOL/Controllers/ControllerChampions.cs | 33 ++- 3 files changed, 237 insertions(+), 120 deletions(-) create mode 100644 Sources/EFLol/DBDataManager/ExtensionsDataManager.cs diff --git a/Sources/EFLol/DBDataManager/EFDataManager.cs b/Sources/EFLol/DBDataManager/EFDataManager.cs index 6dc5dda..9c3ab0e 100644 --- a/Sources/EFLol/DBDataManager/EFDataManager.cs +++ b/Sources/EFLol/DBDataManager/EFDataManager.cs @@ -1,22 +1,23 @@ -using Model; +using Microsoft.EntityFrameworkCore; +using Model; namespace EFLol.DBDataManager { - public class EFDataManager : IDataManager - { + public class EFDataManager : IDataManager + { public IChampionsManager ChampionsMgr => new EFChampionManager(); public ISkinsManager SkinsMgr => throw new NotImplementedException(); - public IRunesManager RunesMgr => throw new NotImplementedException(); + public IRunesManager RunesMgr => throw new NotImplementedException(); - public IRunePagesManager RunePagesMgr => throw new NotImplementedException(); - } + public IRunePagesManager RunePagesMgr => throw new NotImplementedException(); + } - public class EFChampionManager : IChampionsManager - { - private MyDbContext _context; + public class EFChampionManager : IChampionsManager + { + private MyDbContext _context; public EFChampionManager() { @@ -24,111 +25,141 @@ namespace EFLol.DBDataManager } public async Task AddItem(Champion? item) - { - if (item == null) - { - return null; - } - var addItem = await _context.AddAsync(item); - await _context.SaveChangesAsync(); - return addItem.Entity; - - // Va chercher les info du context (Context.champions.get)(DbSet) et les map en champion model - // Dans Program.cs de API rajouter un scope (AddScope ) -> Ca va dire que a chaque fois que j'utilise un IDataManager, il va créer un EFDataManager - } - - - public async Task DeleteItem(Champion? item) - { - if (item == null) - { - return false; - } - var deletedItem = _context.Remove(item); - await _context.SaveChangesAsync(); - return true; - } - - private Func filterByName = (champion, substring) => - champion.Name.Contains(substring, StringComparison.InvariantCultureIgnoreCase); - - - public Task UpdateItem(Champion? oldItem, Champion? newItem) - { - throw new NotImplementedException(); - } + { + if (item == null) + { + throw new Exception("Item is null"); + } + + _context.Add(item.ChampionToEntity()); + _context.SaveChanges(); + return item; + } + + + public async Task DeleteItem(Champion? item) + { + if (item == null) + { + return false; + } + + var champ = _context.Champions.Select(c => c == item.ChampionToEntity()); + + if (champ.Count() < 1) + { + return false; + } + + _context.Champions.Remove(item.ChampionToEntity()); + _context.SaveChanges(); + return true; + } + + + public async Task UpdateItem(Champion? oldItem, Champion? newItem) + { + if (oldItem != null && newItem != null) + { + var champEntity = await _context.Champions.FirstOrDefaultAsync(c => c.Name == oldItem.Name); + if (champEntity == null) + { + throw new Exception("Champion not found in database"); + } + champEntity.Bio = newItem.Bio; + _context.SaveChanges(); + return champEntity.ChampionToPoco(); + } + throw new Exception("Invalid input parameters"); + } + public async Task GetNbItems() => _context.Champions.Count(); - public async Task> GetItems(int index, int count, string? orderingPropertyName = null, bool @descending = false) - { - IEnumerable champions = _context.Champions.Skip(index * count).Take(count).OrderBy(champion => orderingPropertyName).Select(champion => champion.ChampionToPoco()); + + public async Task> GetItems(int index, int count, string? orderingPropertyName = null, + bool descending = false) + { + IEnumerable champions = _context.Champions.Skip(index * count) + .Take(count) + .OrderBy(champions => orderingPropertyName) + .Select(champions => champions.ChampionToPoco()); return champions; } - public Task GetNbItemsByName(string substring) - { - throw new NotImplementedException(); - } - - public Task> GetItemsByName(string substring, int index, int count, string? orderingPropertyName = null, - bool @descending = false) - { - throw new NotImplementedException(); - } - - - public Task GetNbItemsByCharacteristic(string charName) - { - throw new NotImplementedException(); - } - - public Task> GetItemsByCharacteristic(string charName, int index, int count, string? orderingPropertyName = null, - bool @descending = false) - { - throw new NotImplementedException(); - } - - public Task GetNbItemsByClass(ChampionClass championClass) - { - throw new NotImplementedException(); - } - - public Task> GetItemsByClass(ChampionClass championClass, int index, int count, string? orderingPropertyName = null, - bool @descending = false) - { - throw new NotImplementedException(); - } - - public Task GetNbItemsBySkill(Skill? skill) - { - throw new NotImplementedException(); - } - - public Task> GetItemsBySkill(Skill? skill, int index, int count, string? orderingPropertyName = null, bool @descending = false) - { - throw new NotImplementedException(); - } - - public Task GetNbItemsByRunePage(RunePage? runePage) - { - throw new NotImplementedException(); - } - - public Task> GetItemsByRunePage(RunePage? runePage, int index, int count, string? orderingPropertyName = null, - bool @descending = false) - { - throw new NotImplementedException(); - } - - public Task GetNbItemsBySkill(string skill) - { - throw new NotImplementedException(); - } - - public Task> GetItemsBySkill(string skill, int index, int count, string? orderingPropertyName = null, bool @descending = false) - { - throw new NotImplementedException(); - } - } -} + + private Func filterByName = (champion, substring) => + champion.Name.IndexOf(substring, StringComparison.InvariantCultureIgnoreCase) >= 0; + + + public Task> GetItemsByName(string substring, int index, int count, + string? orderingPropertyName = null, bool descending = false) + => _context.Champions.Select(champion => champion.ChampionToPoco()) + .GetItemsWithFilterAndOrdering(champ => filterByName(champ, substring), index, count, + orderingPropertyName, descending); + + public Task GetNbItemsByName(string substring) + { + throw new NotImplementedException(); + } + + + public Task GetNbItemsByCharacteristic(string charName) + { + throw new NotImplementedException(); + } + + public Task> GetItemsByCharacteristic(string charName, int index, int count, + string? orderingPropertyName = null, + bool @descending = false) + { + throw new NotImplementedException(); + } + + public Task GetNbItemsByClass(ChampionClass championClass) + { + throw new NotImplementedException(); + } + + public Task> GetItemsByClass(ChampionClass championClass, int index, int count, + string? orderingPropertyName = null, + bool @descending = false) + { + throw new NotImplementedException(); + } + + public Task GetNbItemsBySkill(Skill? skill) + { + throw new NotImplementedException(); + } + + public Task> GetItemsBySkill(Skill? skill, int index, int count, + string? orderingPropertyName = null, bool @descending = false) + { + throw new NotImplementedException(); + } + + public Task GetNbItemsByRunePage(RunePage? runePage) + { + throw new NotImplementedException(); + } + + public Task> GetItemsByRunePage(RunePage? runePage, int index, int count, + string? orderingPropertyName = null, + bool @descending = false) + { + throw new NotImplementedException(); + } + + public Task GetNbItemsBySkill(string skill) + { + throw new NotImplementedException(); + } + + public Task> GetItemsBySkill(string skill, int index, int count, + string? orderingPropertyName = null, bool @descending = false) + { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/Sources/EFLol/DBDataManager/ExtensionsDataManager.cs b/Sources/EFLol/DBDataManager/ExtensionsDataManager.cs new file mode 100644 index 0000000..3b7986c --- /dev/null +++ b/Sources/EFLol/DBDataManager/ExtensionsDataManager.cs @@ -0,0 +1,71 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace EFLol.DBDataManager +{ + static class ExtensionsDataManager + { + internal static Task> GetItemsWithFilterAndOrdering(this IEnumerable collection, + Func filter, int index, int count, string? orderingPropertyName = null, bool descending = false) + { + IEnumerable temp = collection; + temp = temp.Where(item => filter(item)); + if (orderingPropertyName != null) + { + var prop = typeof(T).GetProperty(orderingPropertyName!); + if (prop != null) + { + temp = descending + ? temp.OrderByDescending(item => prop.GetValue(item)) + : temp.OrderBy(item => prop.GetValue(item)); + } + } + + return Task.FromResult>(temp.Skip(index * count).Take(count)); + } + + internal static Task GetNbItemsWithFilter(this IEnumerable collection, Func filter) + { + return Task.FromResult(collection.Count(item => filter(item))); + } + + internal static Task AddItem(this IList collection, T? item) + { + if (item == null || collection.Contains(item)) + { + return Task.FromResult(default(T)); + } + + collection.Add(item); + return Task.FromResult(item); + } + + internal static Task DeleteItem(this IList collection, T? item) + { + if (item == null) + { + return Task.FromResult(false); + } + + bool result = collection.Remove(item!); + return Task.FromResult(result); + } + + internal static Task UpdateItem(this IList collection, T? oldItem, T? newItem) + { + if (oldItem == null || newItem == null) return Task.FromResult(default(T)); + + if (!collection.Contains(oldItem)) + { + return Task.FromResult(default(T)); + } + + collection.Remove(oldItem!); + collection.Add(newItem!); + return Task.FromResult(newItem); + } + } +} \ No newline at end of file diff --git a/Sources/apiLOL/Controllers/ControllerChampions.cs b/Sources/apiLOL/Controllers/ControllerChampions.cs index da7af5c..38435e3 100644 --- a/Sources/apiLOL/Controllers/ControllerChampions.cs +++ b/Sources/apiLOL/Controllers/ControllerChampions.cs @@ -27,25 +27,25 @@ namespace apiLOL.Controllers [ProducesResponseType(typeof(ChampionPageDTO), 200)] public async Task GetChampions([FromQuery] int index = 0, int count = 10, string? name = "") { - //FromQuery permet de filtrer dans la collection de champions en fonction du nom - // Possible de faire une classe PageRequest pour gérer les paramètres index et count _logger.LogInformation($"methode Get de ControllerChampions appelée"); int nbChampions = await _dataManager.GetNbItems(); _logger.LogInformation($"Nombre de champions : {nbChampions}"); - var champs = (await _dataManager.GetItems(index, count)).Select(Model => Model.ToDTO()); + var champs = (await _dataManager.GetItemsByName(name, index, int.MaxValue)) + .Where(champ => string.IsNullOrEmpty(name) || champ.Name.Contains(name, StringComparison.InvariantCultureIgnoreCase)) + .Take(count) + .Select(Model => Model.ToDTO()); var page = new ChampionPageDTO { Data = champs, Index = index, - Count = count, + Count = champs.Count(), TotalCount = nbChampions }; return Ok(page); } - [HttpGet] [Route("{name}")] [ProducesResponseType(typeof(ChampionDTO), 200)] @@ -54,8 +54,15 @@ namespace apiLOL.Controllers _logger.LogInformation($"methode GetChampion de ControllerChampions appelée avec le paramètre {name}"); try { - var champs = (await _dataManager.GetItemsByName(name, 0, 1)); - return Ok(champs.First().ToDTO()); + var champs = await _dataManager.GetItemsByName(name, 0, 1); + if (champs.Any()) + { + return Ok(champs.First().ToDTO()); + } + else + { + return NotFound(); + } } catch (Exception ex) { @@ -71,18 +78,26 @@ namespace apiLOL.Controllers _logger.LogInformation($"methode Post de ControllerChampions appelée avec le paramètre {champDTO.Name}"); try { + // Check if the champion already exists in the database + var champs = await _dataManager.GetItemsByName(champDTO.Name, 0, 1); + if (champs.Any()) + { + return BadRequest("le champion existe deja"); + } + Champion tmp = champDTO.ToModel(); Champion champion = await _dataManager.AddItem(tmp); ChampionDTO dtoChamp = champion.ToDTO(); - return CreatedAtAction(nameof(GetChampionByName), new {name = dtoChamp.Name}, dtoChamp); + return CreatedAtAction(nameof(GetChampionByName), new { name = dtoChamp.Name }, dtoChamp); } catch (Exception ex) { _logger.LogError($"erreur methode Post de ControllerChampions: {ex}"); - return BadRequest("le champion existe deja"); + return BadRequest("erreur lors de l'ajout du champion"); } } + [HttpPut("{name}")] public async Task UpdateChampion(string name, string bio) {