UpdateServiceUseCase.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. namespace RackPeek.Domain.Resources.Services.UseCases;
  4. public class UpdateServiceUseCase(IResourceCollection repository) : IUseCase {
  5. public async Task ExecuteAsync(
  6. string name,
  7. string? ip = null,
  8. int? port = null,
  9. string? protocol = null,
  10. string? url = null,
  11. List<string>? runsOn = null,
  12. string? notes = null
  13. ) {
  14. // ToDo pass in properties as inputs, construct the entity in the usecase, ensure optional inputs are nullable
  15. // ToDo validate / normalize all inputs
  16. name = Normalize.ServiceName(name);
  17. ThrowIfInvalid.ResourceName(name);
  18. var service = await repository.GetByNameAsync(name) as Service;
  19. if (service is null)
  20. throw new NotFoundException($"Service '{name}' not found.");
  21. if (ip != null) {
  22. service.Network ??= new Network();
  23. service.Network.Ip = ip;
  24. }
  25. if (protocol != null) {
  26. service.Network ??= new Network();
  27. service.Network.Protocol = protocol;
  28. }
  29. if (url != null) {
  30. service.Network ??= new Network();
  31. service.Network.Url = url;
  32. }
  33. if (port.HasValue) {
  34. service.Network ??= new Network();
  35. service.Network.Port = port.Value;
  36. }
  37. if (runsOn is not null) {
  38. var normalizedParents = new List<string>();
  39. foreach (var parent in runsOn
  40. .Where(p => !string.IsNullOrWhiteSpace(p))
  41. .Select(p => p.Trim())
  42. .Distinct(StringComparer.OrdinalIgnoreCase)) {
  43. ThrowIfInvalid.ResourceName(parent);
  44. Resource? parentSystem = await repository.GetByNameAsync(parent);
  45. if (parentSystem == null)
  46. throw new NotFoundException($"Parent system '{parent}' not found.");
  47. normalizedParents.Add(parent);
  48. }
  49. service.RunsOn = normalizedParents;
  50. }
  51. if (notes != null) service.Notes = notes;
  52. await repository.UpdateAsync(service);
  53. }
  54. }