4
0

RemoveLabelUseCase.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. /// <summary>
  11. /// Removes the label with the given key. No-op if the key does not exist.
  12. /// </summary>
  13. /// <param name="name">Resource name.</param>
  14. /// <param name="key">Label key to remove.</param>
  15. /// <exception cref="NotFoundException">Thrown when the resource does not exist.</exception>
  16. /// <exception cref="ValidationException">Thrown when key fails validation.</exception>
  17. Task ExecuteAsync(string name, string key);
  18. }
  19. /// <summary>
  20. /// Removes a label by key from a resource.
  21. /// </summary>
  22. public class RemoveLabelUseCase<T>(IResourceCollection repo) : IRemoveLabelUseCase<T>
  23. where T : Resource {
  24. /// <inheritdoc />
  25. public async Task ExecuteAsync(string name, string key) {
  26. key = Normalize.LabelKey(key);
  27. name = Normalize.HardwareName(name);
  28. ThrowIfInvalid.ResourceName(name);
  29. ThrowIfInvalid.LabelKey(key);
  30. Resource? resource = await repo.GetByNameAsync(name);
  31. if (resource is null)
  32. throw new NotFoundException($"Resource '{name}' not found.");
  33. if (!resource.Labels.Remove(key))
  34. return;
  35. await repo.UpdateAsync(resource);
  36. }
  37. }