AddPortUseCase.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources;
  4. using RackPeek.Domain.Resources.Servers;
  5. using RackPeek.Domain.Resources.SubResources;
  6. namespace RackPeek.Domain.UseCases.Ports;
  7. public interface IAddPortUseCase<T> : IResourceUseCase<T>
  8. where T : Resource
  9. {
  10. public Task ExecuteAsync(
  11. string name,
  12. string? type,
  13. double? speed,
  14. int? ports);
  15. }
  16. public class AddPortUseCase<T>(IResourceCollection repository) : IAddPortUseCase<T> where T : Resource
  17. {
  18. public async Task ExecuteAsync(
  19. string name,
  20. string? type,
  21. double? speed,
  22. int? ports)
  23. {
  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);
  29. ThrowIfInvalid.NicType(nicType);
  30. var 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. pr.Ports ??= new List<Port>();
  34. pr.Ports.Add(new Port
  35. {
  36. Type = nicType,
  37. Speed = speed,
  38. Count = ports
  39. });
  40. await repository.UpdateAsync(resource);
  41. }
  42. }