UpdatePortUseCase.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources;
  4. using RackPeek.Domain.Resources.Connections;
  5. using RackPeek.Domain.Resources.Servers;
  6. using RackPeek.Domain.Resources.SubResources;
  7. namespace RackPeek.Domain.UseCases.Ports;
  8. public interface IUpdatePortUseCase<T> : IResourceUseCase<T>
  9. where T : Resource {
  10. public Task ExecuteAsync(
  11. string name,
  12. int index,
  13. string? type,
  14. double? speed,
  15. int? ports);
  16. }
  17. public class UpdatePortUseCase<T>(IResourceCollection repository) : IUpdatePortUseCase<T> where T : Resource {
  18. public async Task ExecuteAsync(
  19. string name,
  20. int index,
  21. string? type,
  22. double? speed,
  23. int? ports) {
  24. // ToDo pass in properties as inputs, construct the entity in the usecase, ensure optional inputs are nullable
  25. // ToDo validate / normalize all inputs
  26. name = Normalize.HardwareName(name);
  27. ThrowIfInvalid.ResourceName(name);
  28. var nicType = Normalize.NicType(type ?? string.Empty);
  29. ThrowIfInvalid.NicType(nicType);
  30. T resource = await repository.GetByNameAsync<T>(name)
  31. ?? throw new NotFoundException($"Resource '{name}' not found.");
  32. if (resource is not IPortResource pr) throw new NotFoundException($"Resource '{name}' not found.");
  33. if (pr.Ports == null || index < 0 || index >= pr.Ports.Count)
  34. throw new NotFoundException($"Port index {index} not found on '{name}'.");
  35. Port nic = pr.Ports[index];
  36. var oldCount = nic.Count ?? 0;
  37. var newCount = ports ?? oldCount;
  38. if (newCount < oldCount)
  39. for (var i = newCount; i < oldCount; i++)
  40. await repository.RemoveConnectionsForPortAsync(new PortReference {
  41. Resource = name,
  42. PortGroup = index,
  43. PortIndex = i
  44. });
  45. nic.Type = nicType;
  46. nic.Speed = speed;
  47. nic.Count = ports;
  48. await repository.UpdateAsync(resource);
  49. }
  50. }