RemoveLabelUseCase.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources;
  4. namespace RackPeek.Domain.UseCases.Labels;
  5. /// <summary>
  6. /// Removes a label by key from a resource.
  7. /// </summary>
  8. public interface IRemoveLabelUseCase<T> : IResourceUseCase<T>
  9. where T : Resource
  10. {
  11. /// <summary>
  12. /// Removes the label with the given key. No-op if the key does not exist.
  13. /// </summary>
  14. /// <param name="name">Resource name.</param>
  15. /// <param name="key">Label key to remove.</param>
  16. /// <exception cref="NotFoundException">Thrown when the resource does not exist.</exception>
  17. /// <exception cref="ValidationException">Thrown when key fails validation.</exception>
  18. Task ExecuteAsync(string name, string key);
  19. }
  20. /// <summary>
  21. /// Removes a label by key from a resource.
  22. /// </summary>
  23. public class RemoveLabelUseCase<T>(IResourceCollection repo) : IRemoveLabelUseCase<T>
  24. where T : Resource
  25. {
  26. /// <inheritdoc />
  27. public async Task ExecuteAsync(string name, string key)
  28. {
  29. key = Normalize.LabelKey(key);
  30. name = Normalize.HardwareName(name);
  31. ThrowIfInvalid.ResourceName(name);
  32. ThrowIfInvalid.LabelKey(key);
  33. var resource = await repo.GetByNameAsync(name);
  34. if (resource is null)
  35. throw new NotFoundException($"Resource '{name}' not found.");
  36. if (!resource.Labels.Remove(key))
  37. return;
  38. await repo.UpdateAsync(resource);
  39. }
  40. }