Added validation for allocation editor

This commit is contained in:
Masu-Baumgartner
2024-09-03 08:49:43 +02:00
parent 30d912e412
commit 278c8acf16
3 changed files with 42 additions and 10 deletions

View File

@@ -2,6 +2,9 @@ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MoonCore.Extended.Abstractions;
using MoonCore.Helpers;
using Moonlight.ApiServer.App.Attributes;
using Moonlight.ApiServer.App.Exceptions;
using Moonlight.ApiServer.App.Helpers;
using MoonlightServers.ApiServer.Database.Entities;
using MoonlightServers.Shared.Http.Requests.Admin.Allocations;
@@ -20,6 +23,41 @@ public class NodeAllocationsController : BaseSubCrudController<Node, Allocation,
PermissionPrefix = "admin.servers.nodes.allocations";
}
[HttpPost]
[RequirePermission("admin.servers.nodes.allocations.create")]
public override async Task<ActionResult<DetailAllocationResponse>> Create(CreateAllocationRequest request)
{
if (ItemRepository.Get().Any(x => x.IpAddress == request.IpAddress && x.Port == request.Port))
throw new ApiException("An allocation with this ip and port already exists", statusCode: 400);
var item = Mapper.Map<Allocation>(request!);
Property.Invoke(RootItem).Add(item);
RootItemRepository.Update(RootItem);
var response = Mapper.Map<DetailAllocationResponse>(item);
return Ok(response);
}
[HttpPatch("{id}")]
[RequirePermission("admin.servers.nodes.allocations.create")]
public override async Task<ActionResult<DetailAllocationResponse>> Update(int id, UpdateAllocationRequest request)
{
var item = LoadItemById(id);
if (ItemRepository.Get().Any(x => x.IpAddress == request.IpAddress && x.Port == request.Port && x.Id != item.Id))
throw new ApiException("An allocation with this ip and port already exists", statusCode: 400);
var mappedItem = Mapper.Map(item, request!, ignoreNullValues: true);
ItemRepository.Update(mappedItem);
var response = Mapper.Map<DetailAllocationResponse>(mappedItem);
return Ok(response);
}
protected override IEnumerable<Node> IncludeRelations(IQueryable<Node> items)
=> items.Include(x => x.Allocations);
}