Add items crud to api
This commit is contained in:
69
api/src/Controllers/ItemsController.cs
Normal file
69
api/src/Controllers/ItemsController.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
|
||||
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>>> getItemss() {
|
||||
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(Item item) {
|
||||
|
||||
var created = await service_.Create(item);
|
||||
|
||||
return CreatedAtAction(
|
||||
nameof(getItem),
|
||||
new { id = created.Id },
|
||||
created
|
||||
);
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
[HttpPut("{id}")]
|
||||
public async Task<ActionResult<Item>> updateItem(int id, Item item) {
|
||||
|
||||
var updated = await service_.Update(item);
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user