All checks were successful
Build and Deploy API / build-and-deploy (push) Successful in 8s
86 lines
2.0 KiB
C#
86 lines
2.0 KiB
C#
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
|
|
using agologumApi.Models;
|
|
using agologumApi.Services;
|
|
|
|
[ApiController]
|
|
[Route("api/[controller]")]
|
|
public class ItemsController : ControllerBase {
|
|
|
|
private readonly ItemService service_;
|
|
|
|
public ItemsController(ItemService service) {
|
|
service_ = service;
|
|
}
|
|
|
|
[AllowAnonymous] // accessible if not authorized
|
|
[HttpGet]
|
|
public async Task<ActionResult<List<Item>>> getItems() {
|
|
return Ok(await service_.GetAll());
|
|
}
|
|
|
|
[AllowAnonymous]
|
|
[HttpGet("{id:int}")]
|
|
public async Task<ActionResult<Item>> getItem(int id) {
|
|
|
|
var item = await service_.Get(id);
|
|
|
|
if (item == null) return NotFound();
|
|
|
|
return Ok(item);
|
|
}
|
|
|
|
[Authorize] // testing the authorization
|
|
[HttpPost]
|
|
public async Task<ActionResult<Item>> createItem(ItemDto item) {
|
|
|
|
Item newItem = new Item {
|
|
Name = item.Name,
|
|
Description = item.Description,
|
|
CreatedAt = DateTime.UtcNow,
|
|
LastEditedAt = DateTime.UtcNow
|
|
};
|
|
|
|
var created = await service_.Create(newItem);
|
|
|
|
return CreatedAtAction(
|
|
nameof(getItem),
|
|
new { id = created.Id },
|
|
created
|
|
);
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpPut("{id}")]
|
|
public async Task<ActionResult<Item>> updateItem(int id, ItemDto item) {
|
|
|
|
Item? oldItem = await service_.Get(id);
|
|
if(oldItem == null) return NotFound();
|
|
|
|
Item updatedItem = new Item {
|
|
Name = item.Name,
|
|
Description = item.Description,
|
|
CreatedAt = oldItem.CreatedAt,
|
|
LastEditedAt = DateTime.UtcNow
|
|
};
|
|
|
|
var updated = await service_.Update(updatedItem);
|
|
|
|
if (updated == null) return NotFound();
|
|
|
|
return Ok(updated);
|
|
}
|
|
|
|
[Authorize]
|
|
[HttpDelete("{id}")]
|
|
public async Task<ActionResult> deleteItem(int id) {
|
|
|
|
var success = await service_.Delete(id);
|
|
|
|
if (!success) return NotFound();
|
|
|
|
return NoContent();
|
|
}
|
|
} |