79 lines
2.6 KiB
C#
79 lines
2.6 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using T120B165_ImgBoard.Dtos;
|
|
using T120B165_ImgBoard.Dtos.Tag;
|
|
using T120B165_ImgBoard.Models;
|
|
using T120B165_ImgBoard.Services;
|
|
using T120B165_ImgBoard.Utils;
|
|
|
|
namespace T120B165_ImgBoard.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/tags")]
|
|
public class TagController(ITagService tagService) : ControllerBase
|
|
{
|
|
[HttpPost]
|
|
[ProducesResponseType(StatusCodes.Status201Created)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status409Conflict)]
|
|
public async Task<ActionResult<Tag>> Create(CreateTagDto dto)
|
|
{
|
|
// Check if tag exists, if it does, throw a conflict
|
|
var existingTag = await tagService.GetByName(dto.Name);
|
|
if (existingTag != null)
|
|
{
|
|
return Problem(
|
|
detail: "Tag with such name already exists.",
|
|
statusCode: StatusCodes.Status409Conflict
|
|
);
|
|
}
|
|
|
|
var createdTag = await tagService.Create(dto.Type, dto.Name);
|
|
return CreatedAtAction(nameof(Get), new { name = createdTag.Name }, createdTag);
|
|
}
|
|
|
|
[HttpGet]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
public async Task<ActionResult<PagedList<Tag>>> GetAll(int pageNumber = 1)
|
|
{
|
|
return Ok(await tagService.GetAll(pageNumber));
|
|
}
|
|
|
|
[HttpGet("{name}")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<ActionResult<Tag>> Get(string name)
|
|
{
|
|
var tag = await tagService.GetByName(name);
|
|
if (tag == null)
|
|
{
|
|
return NotFound();
|
|
}
|
|
return Ok(tag);
|
|
}
|
|
|
|
[HttpDelete("{name}")]
|
|
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<ActionResult> Delete(string name)
|
|
{
|
|
var deleted = await tagService.DeleteByName(name);
|
|
if (!deleted) return NotFound();
|
|
return NoContent();
|
|
}
|
|
|
|
[HttpPatch("{name}")]
|
|
[ProducesResponseType(StatusCodes.Status200OK)]
|
|
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
|
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
|
public async Task<ActionResult<Tag>> Update(string name, EditTagDto dto)
|
|
{
|
|
var tag = await tagService.GetByName(name);
|
|
if (tag == null) return NotFound();
|
|
var updatedTag = await tagService.Update(tag, dto.Type);
|
|
return Ok(updatedTag);
|
|
}
|
|
}
|