99 lines
2.5 KiB
C#
99 lines
2.5 KiB
C#
using back.context;
|
|
using back.DataModels;
|
|
using back.DTO;
|
|
using back.persistance.blob;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
namespace back.controllers;
|
|
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class PhotosController(PhotoContext photoContext, IBlobStorageService blobStorage) : ControllerBase
|
|
{
|
|
private readonly PhotoContext _photoContext = photoContext;
|
|
|
|
// GET: api/<PhotoController>
|
|
[HttpGet]
|
|
public async Task<ActionResult<IEnumerable<PhotoModel>>> Get([FromQuery] int page = 1, [FromQuery] int pageSize = 20)
|
|
{
|
|
var photos = await _photoContext.GetPage(page, pageSize);
|
|
var totalItems = await _photoContext.GetTotalItems();
|
|
|
|
Response.Headers.Append("X-Total-Count", totalItems.ToString());
|
|
return Ok(photos);
|
|
}
|
|
|
|
// GET api/<PhotoController>/5
|
|
[HttpGet("{res}/{id}")]
|
|
public async Task<IActionResult> Get(string res, Guid id)
|
|
{
|
|
var photo = await _photoContext.GetById(id);
|
|
if (photo == null)
|
|
return NotFound();
|
|
|
|
string? filePath = res.ToLower() switch
|
|
{
|
|
"high" => photo.HighResUrl,
|
|
"mid" => photo.MidResUrl,
|
|
"low" or _ => photo.LowResUrl
|
|
};
|
|
|
|
string? mediaType = res.ToLower() switch
|
|
{
|
|
"high" => $"image/{photo.Extension}",
|
|
"mid" or "low" or _ => "image/webp",
|
|
};
|
|
|
|
if (filePath == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
var file = await blobStorage.GetBytesAsync(filePath);
|
|
if (file == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
|
|
return File(file, mediaType);
|
|
}
|
|
|
|
// POST api/<PhotoController>
|
|
[HttpPost]
|
|
public async Task<IActionResult> Post([FromForm] PhotoFormModel form)
|
|
{
|
|
try
|
|
{
|
|
if (form.Image == null || form.Image.Length == 0)
|
|
return BadRequest("No image uploaded.");
|
|
|
|
await _photoContext.CreateNew(form);
|
|
|
|
return Created();
|
|
}
|
|
catch
|
|
{
|
|
return BadRequest();
|
|
}
|
|
}
|
|
|
|
//// PUT api/<PhotoController>
|
|
[HttpPut]
|
|
public async Task<IActionResult> Put([FromBody] PhotoModel photo)
|
|
{
|
|
await _photoContext.Update(photo);
|
|
return NoContent();
|
|
}
|
|
|
|
// DELETE api/<PhotoController>/5
|
|
[HttpDelete("{id}")]
|
|
public async Task<IActionResult> Delete(Guid id)
|
|
{
|
|
var photo = await _photoContext.GetById(id);
|
|
if (photo == null)
|
|
return NotFound();
|
|
|
|
await _photoContext.Delete(photo);
|
|
return NoContent();
|
|
}
|
|
}
|