AddLabelUseCase.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. /// <summary>
  11. /// Adds or overwrites a label on the resource. If the key already exists, the value is updated.
  12. /// </summary>
  13. /// <param name="name">Resource name.</param>
  14. /// <param name="key">Label key.</param>
  15. /// <param name="value">Label value.</param>
  16. /// <exception cref="NotFoundException">Thrown when the resource does not exist.</exception>
  17. /// <exception cref="ValidationException">Thrown when key or value fails validation.</exception>
  18. Task ExecuteAsync(string name, string key, string value);
  19. }
  20. /// <summary>
  21. /// Adds or updates a key-value label on a resource.
  22. /// </summary>
  23. public class AddLabelUseCase<T>(IResourceCollection repo) : IAddLabelUseCase<T>
  24. where T : Resource {
  25. /// <inheritdoc />
  26. public async Task ExecuteAsync(string name, string key, string value) {
  27. key = Normalize.LabelKey(key);
  28. value = Normalize.LabelValue(value);
  29. name = Normalize.HardwareName(name);
  30. ThrowIfInvalid.ResourceName(name);
  31. ThrowIfInvalid.LabelKey(key);
  32. ThrowIfInvalid.LabelValue(value);
  33. Resource? resource = await repo.GetByNameAsync(name);
  34. if (resource is null)
  35. throw new NotFoundException($"Resource '{name}' not found.");
  36. resource.Labels[key] = value;
  37. await repo.UpdateAsync(resource);
  38. }
  39. }