85 lines
2.8 KiB
C#
85 lines
2.8 KiB
C#
using back.ApiService.context;
|
|
using back.ApiService.models;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace back.ApiService.controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class PhotoController(PhotoContext photoContext) : ControllerBase
|
|
{
|
|
private readonly PhotoContext _photoContext = photoContext;
|
|
|
|
// GET: api/<PhotoController>
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<Photo>>> Get([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
|
|
{
|
|
if (page < 1) page = 1;
|
|
if (pageSize < 1) pageSize = 20;
|
|
|
|
var totalItems = await _photoContext.Photos.CountAsync();
|
|
var photos = await _photoContext.Photos
|
|
.OrderByDescending(p => p.CreatedAt)
|
|
.Skip((page - 1) * pageSize)
|
|
.Take(pageSize)
|
|
.ToListAsync();
|
|
|
|
Response.Headers.Append("X-Total-Count", totalItems.ToString());
|
|
|
|
return Ok(photos);
|
|
}
|
|
|
|
// GET api/<PhotoController>/5
|
|
[HttpGet("{id}")]
|
|
public async Task<ActionResult<Photo>> Get(Guid id)
|
|
{
|
|
var photo = await _photoContext.Photos.FindAsync(id);
|
|
if (photo == null)
|
|
return NotFound();
|
|
return photo;
|
|
}
|
|
|
|
// POST api/<PhotoController>
|
|
[HttpPost]
|
|
public async Task<ActionResult<Photo>> Post([FromForm] string title, [FromForm] string description, [FromForm] List<string> tags, [FromForm] List<string> personsIn, [FromForm] IFormFile image)
|
|
{
|
|
if (image == null || image.Length == 0)
|
|
return BadRequest("No image uploaded.");
|
|
|
|
var photo = PhotoBuilder.Build(title, description, tags, personsIn, image);
|
|
|
|
// Guarda la información en la base de datos
|
|
_photoContext.Photos.Add(photo);
|
|
await _photoContext.SaveChangesAsync();
|
|
|
|
return CreatedAtAction(nameof(Get), new { id = photo.Id }, photo);
|
|
}
|
|
|
|
// PUT api/<PhotoController>/5
|
|
[HttpPut("{id}")]
|
|
public async Task<IActionResult> Put(Guid id, [FromBody] Photo photo)
|
|
{
|
|
if (id != photo.Id)
|
|
return BadRequest();
|
|
|
|
_photoContext.Entry(photo).State = EntityState.Modified;
|
|
await _photoContext.SaveChangesAsync();
|
|
return NoContent();
|
|
}
|
|
|
|
// DELETE api/<PhotoController>/5
|
|
[HttpDelete("{id}")]
|
|
public async Task<IActionResult> Delete(Guid id)
|
|
{
|
|
var photo = await _photoContext.Photos.FindAsync(id);
|
|
if (photo == null)
|
|
return NotFound();
|
|
|
|
_photoContext.Photos.Remove(photo);
|
|
await _photoContext.SaveChangesAsync();
|
|
return NoContent();
|
|
}
|
|
}
|
|
}
|