Merge_API_EF #8

Merged
kevin.mondejar merged 5 commits from Merge_API_EF into master 3 weeks ago

@ -2,6 +2,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Shared; using Shared;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
@ -13,11 +14,13 @@ namespace Contextlib
{ {
private WTFContext _context; private WTFContext _context;
private GenericRepository<Character> _repo; private GenericRepository<Character> _repo;
private DbImagesManager _dbI;
public DbCharacterManager(WTFContext context) public DbCharacterManager(WTFContext context)
{ {
_context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null."); _context = context ?? throw new ArgumentNullException(nameof(context), "Database context cannot be null.");
_repo = new GenericRepository<Character>(_context); _repo = new GenericRepository<Character>(_context);
_dbI = new DbImagesManager(context);
} }
/// <summary> /// <summary>
@ -32,6 +35,12 @@ namespace Contextlib
{ {
throw new ArgumentNullException(nameof(character), "character cannot be null."); throw new ArgumentNullException(nameof(character), "character cannot be null.");
} }
var image = await _dbI.GetImageByPath(character.Images.ImgPath);
if (image != null)
{
character.IdImage = image.Id;
character.Images = image;
}
_repo.Insert(character); _repo.Insert(character);
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
} }
@ -93,6 +102,12 @@ namespace Contextlib
return lastCharId; return lastCharId;
} }
public async Task<PaginationResult<Character>> GetSomeChar(int page, int count)
{
var charLst = _repo.GetItems(page, count, [nameof(Character.Images)]).ToList();
return new PaginationResult<Character>(charLst.Count, 0, charLst.Count, charLst);
}
/// <summary> /// <summary>
/// Removes a character from the database by its ID. /// Removes a character from the database by its ID.
/// </summary> /// </summary>
@ -119,9 +134,11 @@ namespace Contextlib
if (charac != null) if (charac != null)
{ {
bool change = false; bool change = false;
if (character.IdImage != 0) var image = await _dbI.GetImageByPath(character.Images.ImgPath);
if (image != null)
{ {
charac.IdImage = character.IdImage; charac.IdImage = image.Id;
charac.Images = image;
change = true; change = true;
} }
if (character.Name != null) if (character.Name != null)

@ -35,7 +35,12 @@ namespace Contextlib
public async Task<Images?> GetImageById(int id) public async Task<Images?> GetImageById(int id)
{ {
return _repository.GetById(id); var image = _repository.GetById(id);
if(image == null)
{
throw new KeyNotFoundException($"No image with the id {id}");
}
return image;
} }
public async Task<int> GetLastImageId() public async Task<int> GetLastImageId()

@ -261,6 +261,7 @@ namespace Dto2Entities
Character character = new Character(); Character character = new Character();
character.Id = item.Id; character.Id = item.Id;
character.Name = item.Name; character.Name = item.Name;
character.Images = new Images();
character.Images.ImgPath = item.imagePath ; character.Images.ImgPath = item.imagePath ;
return character; return character;
} }

@ -33,7 +33,7 @@ namespace ServicesApi
public async Task<CharacterDTO> GetCharById(int id) public async Task<CharacterDTO> GetCharById(int id)
{ {
return characterService.GetCharById(id).Result.ToDto(); return (await characterService.GetCharById(id)).ToDto();
} }
public async Task<CharacterDTO> GetCharByName(string name) public async Task<CharacterDTO> GetCharByName(string name)
@ -46,6 +46,12 @@ namespace ServicesApi
return await characterService.GetLastCharId(); return await characterService.GetLastCharId();
} }
public async Task<PaginationResult<CharacterDTO>> GetSomeChar(int page, int count)
{
var characters = (await characterService.GetSomeChar(page, count)).items;
return new PaginationResult<CharacterDTO>(characters.Count(), page, count, characters.ToDto());
}
public async Task RemoveCharacter(int id) public async Task RemoveCharacter(int id)
{ {
await characterService.RemoveCharacter(id); await characterService.RemoveCharacter(id);

@ -7,6 +7,7 @@ using DTO;
using Entity; using Entity;
using Shared; using Shared;
using Dto2Entities; using Dto2Entities;
using static System.Net.Mime.MediaTypeNames;
namespace ServicesApi namespace ServicesApi
{ {
@ -32,7 +33,22 @@ namespace ServicesApi
public async Task<ImageDTO> GetImageById(int id) public async Task<ImageDTO> GetImageById(int id)
{ {
return imageService.GetImageById(id).Result.ToDto(); var image = await imageService.GetImageById(id);
if (image == null)
{
throw new KeyNotFoundException($"No image with the id {id}");
}
return image.ToDto();
}
public async Task<ImageDTO?> GetImageByPath(string path)
{
var image = await imageService.GetImageByPath(path);
if (image == null)
{
return null;
}
return image.ToDto();
} }
public async Task<int> GetLastImageId() public async Task<int> GetLastImageId()

@ -35,5 +35,7 @@ namespace Shared
// Retrieves the unique identifier of the last added character. // Retrieves the unique identifier of the last added character.
Task<int> GetLastCharId(); Task<int> GetLastCharId();
Task<PaginationResult<TChar>> GetSomeChar(int page, int count);
} }
} }

@ -35,5 +35,7 @@ namespace Shared
// Retrieves the last Image ID. // Retrieves the last Image ID.
Task<int> GetLastImageId(); Task<int> GetLastImageId();
Task<TImage?> GetImageByPath(string path);
} }
} }

@ -0,0 +1,135 @@
using System.Net;
using DTO;
using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared;
namespace WfApi.Controllers
{
[ApiController]
[Route("api/v1/character")] //Version API
public class CharacterController : ControllerBase
{
private readonly ICharacterService<CharacterDTO> _character;
private readonly ILogger<CharacterController> _logger;
public CharacterController(ICharacterService<CharacterDTO> characterService, ILogger<CharacterController> logger)
{
_character = characterService;
_logger = logger;
}
[HttpGet("{id}")] // Indiquer que l'id est dans l'URL
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetCharacter(int id)
{
try
{
try
{
var character = await _character.GetCharById(id);
return Ok(character);
}
catch(KeyNotFoundException)
{
return NotFound();
}
}
catch (Exception)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" });
}
}
[HttpGet("all")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetAllSource(int index = 0, int count = 10)
{
try
{
var result = await _character.GetSomeChar(index, count);
if (result != null)
{
return await Task.FromResult<IActionResult>(Ok(result));
}
else
{
return NoContent();
}
}
catch (Exception)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" });
}
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> CreateCharacter([FromBody] CharacterDTO newCharacter)
{
try
{
if (newCharacter == null)
{
return BadRequest(new { message = "Character data is required." });
}
try
{
var existingSource = await _character.GetCharById(newCharacter.Id);
return Conflict(new { message = "A character with this ID already exists." });
}
catch (KeyNotFoundException)
{
await _character.AddCharacter(newCharacter);
return Ok(newCharacter);
}
}
catch (Exception)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" });
}
}
[HttpPut()]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> UpdateCharacter([FromQuery] int id, [FromBody] CharacterDTO updatedCharacter)
{
try
{
if (updatedCharacter == null)
{
return BadRequest(new { message = "new character data is required." });
}
try
{
var existChar = await _character.GetCharById(id);
var result = _character.UpdateCharacter(id, updatedCharacter);
return Ok(result);
}
catch(KeyNotFoundException)
{
return Conflict(new { message = "A character with this ID already exists." });
}
}
catch (Exception)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" });
}
}
}
}

@ -22,6 +22,10 @@ namespace WfApi.Controllers
[HttpGet("{id}")] // Indiquer que l'id est dans l'URL [HttpGet("{id}")] // Indiquer que l'id est dans l'URL
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetCommentary(int id, int index = 0, int count = 5) public async Task<IActionResult> GetCommentary(int id, int index = 0, int count = 5)
{ {
try try

@ -0,0 +1,141 @@
using DTO;
using System.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared;
using Entity;
namespace WfApi.Controllers
{
[ApiController]
[Route("api/v1/image")] //Version API
public class ImageController : ControllerBase
{
private readonly IImagesService<ImageDTO> _img;
private readonly ILogger<ImageController> _logger;
public ImageController(IImagesService<ImageDTO> imgService, ILogger<ImageController> logger)
{
_img = imgService;
_logger = logger;
}
[HttpGet("{id}")] // Indiquer que l'id est dans l'URL
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetImageId(int id)
{
try
{
try
{
var image = await _img.GetImageById(id);
return Ok(image);
}
catch (KeyNotFoundException e)
{
return NotFound();
}
}
catch (Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" });
}
}
[HttpGet("all")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> GetAllImage(int index = 0, int count = 10)
{
try
{
var result = await _img.GetSomeImage(index, count);
if (result == null)
{
return NotFound();
}
return Ok(result);
}
catch (KeyNotFoundException e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" });
}
}
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateImage([FromBody] ImageDTO newImage)
{
try
{
if(newImage == null)
{
return BadRequest(new { message = "Source data is required." });
}
try
{
var existImage = await _img.GetImageById(newImage.IdImage);
return Conflict(new { message = $"A Image with the ID {newImage.IdImage} already exists." });
}
catch(KeyNotFoundException e)
{
var existPath = await _img.GetImageByPath(newImage.ImagePath);
if(existPath == null)
{
await _img.AddImage(newImage);
return Ok(newImage);
}
return Conflict(new { message = $"A Image with the path {newImage.ImagePath} already exists." });
}
}
catch(Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error" });
}
}
[HttpPut()]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> UpdateImage([FromQuery] int id, [FromBody] ImageDTO updatedImage)
{
try
{
if (updatedImage == null)
{
return BadRequest(new { message = "new source data is required." });
}
try
{
var existImage = await _img.GetImageById(id);
var existPath = await _img.GetImageByPath(updatedImage.ImagePath);
if (existPath == null)
{
await _img.UpdateImage(id, updatedImage);
return Ok(updatedImage);
}
return Conflict(new { message = $"A Image with the path {updatedImage.ImagePath} already exists." });
}
catch (KeyNotFoundException e)
{
return Conflict(new { message = $"A Image with the ID {id} dosen't exists." });
}
}
catch (Exception e)
{
return StatusCode((int)HttpStatusCode.InternalServerError, new { message = "Internal Server Error (" + e + ")" });
}
}
}
}
Loading…
Cancel
Save