RemoveCpuUseCase.cs 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using RackPeek.Domain.Helpers;
  2. using RackPeek.Domain.Persistence;
  3. using RackPeek.Domain.Resources;
  4. using RackPeek.Domain.Resources.Servers;
  5. namespace RackPeek.Domain.UseCases.Cpus;
  6. public interface IRemoveCpuUseCase<T> : IResourceUseCase<T>
  7. where T : Resource {
  8. public Task ExecuteAsync(
  9. string name,
  10. int index);
  11. }
  12. public class RemoveCpuUseCase<T>(IResourceCollection repo) : IRemoveCpuUseCase<T> where T : Resource {
  13. public async Task ExecuteAsync(
  14. string name,
  15. int index) {
  16. name = Normalize.HardwareName(name);
  17. ThrowIfInvalid.ResourceName(name);
  18. T resource = await repo.GetByNameAsync<T>(name) ??
  19. throw new NotFoundException($"Resource '{name}' not found.");
  20. if (resource is not ICpuResource cpuResource) return;
  21. cpuResource.Cpus ??= [];
  22. if (index < 0)
  23. throw new NotFoundException($"Please pick a CPU index >= 0 for '{name}'.");
  24. if (cpuResource.Cpus.Count == 0)
  25. throw new NotFoundException($"'{name}' has no CPUs.");
  26. if (index >= cpuResource.Cpus.Count)
  27. throw new NotFoundException($"Please pick a CPU index < {cpuResource.Cpus.Count} for '{name}'.");
  28. cpuResource.Cpus.RemoveAt(index);
  29. await repo.UpdateAsync(resource);
  30. }
  31. }