UpdateSystemUseCase.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. namespace RackPeek.Domain.Resources.SystemResources.UseCases;
  4. public class UpdateSystemUseCase(IResourceCollection repository) : IUseCase {
  5. public async Task ExecuteAsync(
  6. string name,
  7. string? type = null,
  8. string? os = null,
  9. int? cores = null,
  10. double? ram = null,
  11. string? ip = null,
  12. List<string>? runsOn = null,
  13. string? notes = null
  14. ) {
  15. // ToDo pass in properties as inputs, construct the entity in the usecase, ensure optional inputs are nullable
  16. // ToDo validate / normalize all inputs
  17. name = Normalize.SystemName(name);
  18. ThrowIfInvalid.ResourceName(name);
  19. var system = await repository.GetByNameAsync(name) as SystemResource;
  20. if (system is null)
  21. throw new InvalidOperationException($"System '{name}' not found.");
  22. if (!string.IsNullOrWhiteSpace(type)) {
  23. var normalizedSystemType = Normalize.SystemType(type);
  24. ThrowIfInvalid.SystemType(normalizedSystemType);
  25. system.Type = normalizedSystemType;
  26. }
  27. if (!string.IsNullOrWhiteSpace(os))
  28. system.Os = os;
  29. if (cores.HasValue)
  30. system.Cores = cores.Value;
  31. if (ram.HasValue)
  32. system.Ram = ram.Value;
  33. if (ip != null) system.Ip = ip;
  34. if (notes != null) system.Notes = notes;
  35. if (runsOn?.Count > 0)
  36. foreach (var parent in runsOn)
  37. if (!string.IsNullOrWhiteSpace(parent)) {
  38. ThrowIfInvalid.ResourceName(parent);
  39. Resource? parentHardware = await repository.GetByNameAsync(parent);
  40. if (parentHardware == null) throw new NotFoundException($"Parent '{parent}' not found.");
  41. if (parentHardware is not Hardware.Hardware and not SystemResource)
  42. throw new Exception("System cannot run on this resource.");
  43. if (!system.RunsOn.Contains(parent)) system.RunsOn.Add(parent);
  44. }
  45. await repository.UpdateAsync(system);
  46. }
  47. }