AddLabelUseCase.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources;
  4. namespace RackPeek.Domain.UseCases.Labels;
  5. /// <summary>
  6. /// Adds or updates a key-value label on a resource.
  7. /// </summary>
  8. public interface IAddLabelUseCase<T> : IResourceUseCase<T>
  9. where T : Resource
  10. {
  11. /// <summary>
  12. /// Adds or overwrites a label on the resource. If the key already exists, the value is updated.
  13. /// </summary>
  14. /// <param name="name">Resource name.</param>
  15. /// <param name="key">Label key.</param>
  16. /// <param name="value">Label value.</param>
  17. /// <exception cref="NotFoundException">Thrown when the resource does not exist.</exception>
  18. /// <exception cref="ValidationException">Thrown when key or value fails validation.</exception>
  19. Task ExecuteAsync(string name, string key, string value);
  20. }
  21. /// <summary>
  22. /// Adds or updates a key-value label on a resource.
  23. /// </summary>
  24. public class AddLabelUseCase<T>(IResourceCollection repo) : IAddLabelUseCase<T>
  25. where T : Resource
  26. {
  27. /// <inheritdoc />
  28. public async Task ExecuteAsync(string name, string key, string value)
  29. {
  30. key = Normalize.LabelKey(key);
  31. value = Normalize.LabelValue(value);
  32. name = Normalize.HardwareName(name);
  33. ThrowIfInvalid.ResourceName(name);
  34. ThrowIfInvalid.LabelKey(key);
  35. ThrowIfInvalid.LabelValue(value);
  36. var resource = await repo.GetByNameAsync(name);
  37. if (resource is null)
  38. throw new NotFoundException($"Resource '{name}' not found.");
  39. resource.Labels[key] = value;
  40. await repo.UpdateAsync(resource);
  41. }
  42. }