UpdateSystemUseCase.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. {
  6. public async Task ExecuteAsync(
  7. string name,
  8. string? type = null,
  9. string? os = null,
  10. int? cores = null,
  11. double? ram = null,
  12. string? ip = null,
  13. List<string>? runsOn = null,
  14. string? notes = null
  15. )
  16. {
  17. // ToDo pass in properties as inputs, construct the entity in the usecase, ensure optional inputs are nullable
  18. // ToDo validate / normalize all inputs
  19. name = Normalize.SystemName(name);
  20. ThrowIfInvalid.ResourceName(name);
  21. var system = await repository.GetByNameAsync(name) as SystemResource;
  22. if (system is null)
  23. throw new InvalidOperationException($"System '{name}' not found.");
  24. if (!string.IsNullOrWhiteSpace(type))
  25. {
  26. var normalizedSystemType = Normalize.SystemType(type);
  27. ThrowIfInvalid.SystemType(normalizedSystemType);
  28. system.Type = normalizedSystemType;
  29. }
  30. if (!string.IsNullOrWhiteSpace(os))
  31. system.Os = os;
  32. if (cores.HasValue)
  33. system.Cores = cores.Value;
  34. if (ram.HasValue)
  35. system.Ram = ram.Value;
  36. if (ip != null)
  37. {
  38. system.Ip = ip;
  39. }
  40. if (notes != null) system.Notes = notes;
  41. if (runsOn?.Count > 0)
  42. {
  43. foreach(string parent in runsOn) {
  44. if (!string.IsNullOrWhiteSpace(parent)) {
  45. ThrowIfInvalid.ResourceName(parent);
  46. var parentHardware = await repository.GetByNameAsync(parent);
  47. if (parentHardware == null) throw new NotFoundException($"Parent '{parent}' not found.");
  48. if (parentHardware is not Hardware.Hardware and not SystemResource)
  49. {
  50. throw new Exception("System cannot run on this resource.");
  51. }
  52. if (!system.RunsOn.Contains(parent)) system.RunsOn.Add(parent);
  53. }
  54. }
  55. }
  56. await repository.UpdateAsync(system);
  57. }
  58. }