| | | 1 | | using CoWorkingApp.Core.Application.Contracts.Adapters; |
| | | 2 | | using CoWorkingApp.Core.Application.Contracts.Repositories; |
| | | 3 | | using CoWorkingApp.Core.Application.Contracts.Requests; |
| | | 4 | | using CoWorkingApp.Core.Application.Contracts.Services; |
| | | 5 | | using System.ComponentModel.DataAnnotations; |
| | | 6 | | |
| | | 7 | | namespace CoWorkingApp.Core.Application.Abstracts |
| | | 8 | | { |
| | | 9 | | /// <summary> |
| | | 10 | | /// Clase abstracta que proporciona una implementación genérica para servicios que manejan operaciones CRUD básicas. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <typeparam name="TRepository">Tipo de repositorio asociado al servicio.</typeparam> |
| | | 13 | | /// <typeparam name="TEntity">Tipo de entidad que se manejará.</typeparam> |
| | | 14 | | /// <typeparam name="TRequest">Tipo de objeto de solicitud.</typeparam> |
| | | 15 | | /// <typeparam name="TResponse">Tipo de objeto de respuesta.</typeparam> |
| | | 16 | | public abstract class ServiceGeneric<TRepository, TEntity, TRequest, TResponse> : IService<TRequest, TResponse> |
| | | 17 | | where TRepository : IRepository<TEntity> |
| | | 18 | | where TEntity : EntityBase |
| | | 19 | | where TRequest : IRequest |
| | | 20 | | where TResponse : ResponseMessage, new() |
| | | 21 | | { |
| | | 22 | | protected readonly TRepository _repository; |
| | | 23 | | protected readonly IMapperAdapter _mapper; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Constructor de la clase ServiceGeneric. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <param name="repository">El repositorio asociado al servicio.</param> |
| | | 29 | | /// <param name="mapper">El adaptador de mapeo utilizado para mapear entre tipos de entidades y DTO.</param> |
| | 181 | 30 | | protected ServiceGeneric(TRepository repository, IMapperAdapter mapper) |
| | 181 | 31 | | { |
| | 181 | 32 | | _repository = repository ?? throw new ArgumentNullException(nameof(repository)); |
| | 178 | 33 | | _mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); |
| | 175 | 34 | | } |
| | | 35 | | |
| | | 36 | | /// <summary> |
| | | 37 | | /// Maneja las excepciones y construye una respuesta de error coherente. |
| | | 38 | | /// </summary> |
| | | 39 | | /// <param name="ex">La excepción que se va a manejar.</param> |
| | | 40 | | /// <returns>Un objeto de respuesta que representa el error.</returns> |
| | | 41 | | protected TResponse HandleException(Exception ex) |
| | 123 | 42 | | { |
| | 123 | 43 | | return ResponseMessage.HandleException<TResponse>(ex); |
| | 123 | 44 | | } |
| | | 45 | | |
| | | 46 | | // Implementación de métodos de la interfaz IService |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Obtiene todas las entidades de manera asincrónica. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <returns>Una colección de objetos de respuesta.</returns> |
| | | 52 | | public virtual async Task<IEnumerable<TResponse>> GetAllAsync() |
| | 9 | 53 | | { |
| | | 54 | | try |
| | 9 | 55 | | { |
| | | 56 | | // Obtener todas las entidades del repositorio |
| | 9 | 57 | | var entities = await _repository.GetAllAsync(); |
| | | 58 | | |
| | | 59 | | // Mapear las entidades a objetos de respuesta y retornarlos |
| | 6 | 60 | | var responses = _mapper.Map<IEnumerable<TEntity>, IEnumerable<TResponse>>(entities).ToList(); |
| | 12 | 61 | | responses.ForEach(res => res.Success = true); |
| | 6 | 62 | | return responses; |
| | | 63 | | } |
| | 3 | 64 | | catch (Exception ex) |
| | 3 | 65 | | { |
| | | 66 | | // Manejar excepciones inesperadas y generar una respuesta de error |
| | 3 | 67 | | return new List<TResponse> { HandleException(ex) }; |
| | | 68 | | } |
| | 9 | 69 | | } |
| | | 70 | | |
| | | 71 | | /// <summary> |
| | | 72 | | /// Obtiene una entidad por su ID de manera asincrónica. |
| | | 73 | | /// </summary> |
| | | 74 | | /// <param name="id">El ID de la entidad.</param> |
| | | 75 | | /// <returns>Un objeto de respuesta.</returns> |
| | | 76 | | public virtual async Task<TResponse> GetByIdAsync(Guid id) |
| | 9 | 77 | | { |
| | | 78 | | try |
| | 9 | 79 | | { |
| | | 80 | | // Buscar la entidad por su ID en el repositorio. Si no, lanzar una excepción |
| | 9 | 81 | | var entity = await _repository.GetByIdAsync(id) ?? throw new ArgumentException($"Entity with id {id} not |
| | | 82 | | |
| | | 83 | | // Mapear la entidad a un objeto de respuesta y retornarlo |
| | 3 | 84 | | var response = _mapper.Map<TEntity, TResponse>(entity); |
| | 3 | 85 | | response.Success = true; |
| | 3 | 86 | | return response; |
| | | 87 | | } |
| | 3 | 88 | | catch (ArgumentException ex) |
| | 3 | 89 | | { |
| | | 90 | | // Manejar la excepción de entidad no encontrada y generar una respuesta de error |
| | 3 | 91 | | return HandleException(ex); |
| | | 92 | | } |
| | 3 | 93 | | catch (Exception ex) |
| | 3 | 94 | | { |
| | | 95 | | // Manejar excepciones inesperadas y generar una respuesta de error |
| | 3 | 96 | | return HandleException(ex); |
| | | 97 | | } |
| | 9 | 98 | | } |
| | | 99 | | |
| | | 100 | | /// <summary> |
| | | 101 | | /// Crea una nueva entidad de manera asincrónica. |
| | | 102 | | /// </summary> |
| | | 103 | | /// <param name="request">El objeto de solicitud.</param> |
| | | 104 | | /// <returns>Un objeto de respuesta.</returns> |
| | | 105 | | public virtual async Task<TResponse> CreateAsync(TRequest request) |
| | 32 | 106 | | { |
| | | 107 | | try |
| | 32 | 108 | | { |
| | | 109 | | // Verificar si la solicitud es nula |
| | 32 | 110 | | if (request is null) |
| | 3 | 111 | | { |
| | | 112 | | // Si la solicitud es nula, lanzar una excepción |
| | 3 | 113 | | throw new ArgumentNullException("The request object cannot be null"); |
| | | 114 | | } |
| | | 115 | | |
| | | 116 | | // Mapear la solicitud a una entidad |
| | 29 | 117 | | var entity = _mapper.Map<TRequest, TEntity>(request); |
| | | 118 | | |
| | | 119 | | // Validar la entidad |
| | 26 | 120 | | if (!IsValid(entity)) |
| | 18 | 121 | | { |
| | | 122 | | // Si la entidad no es válida, lanzar una excepción |
| | 18 | 123 | | throw new ValidationException("Argument is invalid."); |
| | | 124 | | } |
| | | 125 | | |
| | | 126 | | // Agregar la entidad al repositorio |
| | 8 | 127 | | var added = await _repository.AddAsync(entity); |
| | | 128 | | |
| | | 129 | | // Verificar si la entidad fue agregada correctamente |
| | 8 | 130 | | if (!added) |
| | 3 | 131 | | { |
| | | 132 | | // Si la entidad no fue agregada, lanzar una excepción |
| | 3 | 133 | | throw new InvalidOperationException("The entity could not be added."); |
| | | 134 | | } |
| | | 135 | | |
| | | 136 | | // Mapear la entidad a un objeto de respuesta y retornarlo |
| | 5 | 137 | | var response = _mapper.Map<TEntity, TResponse>(entity); |
| | 5 | 138 | | response.Success = true; |
| | 5 | 139 | | return response; |
| | | 140 | | } |
| | 3 | 141 | | catch (ArgumentNullException ex) |
| | 3 | 142 | | { |
| | | 143 | | // Manejar la excepción de argumento nulo y generar una respuesta de error |
| | 3 | 144 | | return HandleException(ex); |
| | | 145 | | } |
| | 18 | 146 | | catch (ValidationException ex) |
| | 18 | 147 | | { |
| | | 148 | | // Manejar la excepción de validación y generar una respuesta de error |
| | 18 | 149 | | return HandleException(ex); |
| | | 150 | | } |
| | 3 | 151 | | catch (InvalidOperationException ex) |
| | 3 | 152 | | { |
| | | 153 | | // Manejar la excepción de operación no válida y generar una respuesta de error |
| | 3 | 154 | | return HandleException(ex); |
| | | 155 | | } |
| | 3 | 156 | | catch (Exception ex) |
| | 3 | 157 | | { |
| | | 158 | | // Manejar excepciones inesperadas y generar una respuesta de error |
| | 3 | 159 | | return HandleException(ex); |
| | | 160 | | } |
| | 32 | 161 | | } |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// ACTualiza una entidad existente de manera asincrónica. |
| | | 165 | | /// </summary> |
| | | 166 | | /// <param name="id">El ID de la entidad.</param> |
| | | 167 | | /// <param name="request">El objeto de solicitud.</param> |
| | | 168 | | /// <returns>Un objeto de respuesta.</returns> |
| | | 169 | | public virtual async Task<TResponse> UpdateAsync(Guid id, TRequest request) |
| | 50 | 170 | | { |
| | | 171 | | try |
| | 50 | 172 | | { |
| | | 173 | | // Verificar si la solicitud es nula |
| | 50 | 174 | | if (request is null) |
| | 3 | 175 | | { |
| | | 176 | | // Si la solicitud es nula, lanzar una excepción |
| | 3 | 177 | | throw new ArgumentNullException("The request object cannot be null"); |
| | | 178 | | } |
| | | 179 | | |
| | | 180 | | // Obtener la entidad existente por su ID. Si no, lanzar una excepción |
| | 47 | 181 | | var existingEntity = await _repository.GetByIdAsync(id) ?? throw new ArgumentException($"Entity with id |
| | | 182 | | |
| | | 183 | | // ACTualizar las propiedades de la entidad existente con los valores de la solicitud |
| | 44 | 184 | | var updatedEntity = UpdateProperties(existingEntity, request); |
| | | 185 | | |
| | | 186 | | // Validar la entidad actualizada |
| | 44 | 187 | | if (!IsValid(updatedEntity)) |
| | 18 | 188 | | { |
| | | 189 | | // Si la entidad no es válida, lanzar una excepción |
| | 18 | 190 | | throw new ValidationException("Argument is invalid."); |
| | | 191 | | } |
| | | 192 | | |
| | | 193 | | // ACTualizar la entidad en el repositorio |
| | 26 | 194 | | bool updated = await _repository.UpdateAsync(updatedEntity); |
| | | 195 | | |
| | | 196 | | // Verificar si la entidad fue actualizada correctamente |
| | 26 | 197 | | if (!updated) |
| | 5 | 198 | | { |
| | | 199 | | // Si la entidad no fue actualizada, lanzar una excepción |
| | 5 | 200 | | throw new InvalidOperationException("The entity could not be updated."); |
| | | 201 | | } |
| | | 202 | | |
| | | 203 | | // Mapear la entidad actualizada a un objeto de respuesta y retornarlo |
| | 21 | 204 | | var response = _mapper.Map<TEntity, TResponse>(updatedEntity); |
| | 16 | 205 | | response.Success = true; |
| | 16 | 206 | | return response; |
| | | 207 | | } |
| | 3 | 208 | | catch (ArgumentNullException ex) |
| | 3 | 209 | | { |
| | | 210 | | // Manejar la excepción de argumento nulo y generar una respuesta de error |
| | 3 | 211 | | return HandleException(ex); |
| | | 212 | | } |
| | 3 | 213 | | catch (ArgumentException ex) |
| | 3 | 214 | | { |
| | | 215 | | // Manejar la excepción de argumento inválido y generar una respuesta de error |
| | 3 | 216 | | return HandleException(ex); |
| | | 217 | | } |
| | 18 | 218 | | catch (ValidationException ex) |
| | 18 | 219 | | { |
| | | 220 | | // Manejar la excepción de validación y generar una respuesta de error |
| | 18 | 221 | | return HandleException(ex); |
| | | 222 | | } |
| | 5 | 223 | | catch (InvalidOperationException ex) |
| | 5 | 224 | | { |
| | | 225 | | // Manejar la excepción de operación no válida y generar una respuesta de error |
| | 5 | 226 | | return HandleException(ex); |
| | | 227 | | } |
| | 5 | 228 | | catch (Exception ex) |
| | 5 | 229 | | { |
| | | 230 | | // Manejar excepciones inesperadas y generar una respuesta de error |
| | 5 | 231 | | return HandleException(ex); |
| | | 232 | | } |
| | 50 | 233 | | } |
| | | 234 | | |
| | | 235 | | /// <summary> |
| | | 236 | | /// Elimina una entidad por su ID de manera asincrónica. |
| | | 237 | | /// </summary> |
| | | 238 | | /// <param name="id">El ID de la entidad.</param> |
| | | 239 | | /// <returns>Un objeto de respuesta.</returns> |
| | | 240 | | public virtual async Task<TResponse> DeleteAsync(Guid id) |
| | 24 | 241 | | { |
| | | 242 | | try |
| | 24 | 243 | | { |
| | | 244 | | // Obtener la entidad por su ID. Si no, lanzar una excepción |
| | 24 | 245 | | var entity = await _repository.GetByIdAsync(id) ?? throw new ArgumentNullException($"Entity with id {id} |
| | | 246 | | |
| | | 247 | | // Eliminar la entidad del repositorio |
| | 21 | 248 | | var deleted = await _repository.RemoveAsync(entity); |
| | | 249 | | |
| | | 250 | | // Verificar si la entidad fue eliminada correctamente |
| | 21 | 251 | | if (!deleted) |
| | 7 | 252 | | { |
| | | 253 | | // Si la entidad no fue eliminada, lanzar una excepción |
| | 7 | 254 | | throw new InvalidOperationException("The entity could not be deleted."); |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | // Mapear la entidad eliminada a un objeto de respuesta y retornarlo |
| | 14 | 258 | | var response = _mapper.Map<TEntity, TResponse>(entity); |
| | 7 | 259 | | response.Success = true; |
| | 7 | 260 | | return response; |
| | | 261 | | } |
| | 3 | 262 | | catch (ArgumentNullException ex) |
| | 3 | 263 | | { |
| | | 264 | | // Manejar la excepción de argumento nulo y generar una respuesta de error |
| | 3 | 265 | | return HandleException(ex); |
| | | 266 | | } |
| | 7 | 267 | | catch (InvalidOperationException ex) |
| | 7 | 268 | | { |
| | | 269 | | // Manejar la excepción de operación no válida y generar una respuesta de error |
| | 7 | 270 | | return HandleException(ex); |
| | | 271 | | } |
| | 7 | 272 | | catch (Exception ex) |
| | 7 | 273 | | { |
| | | 274 | | // Manejar excepciones inesperadas y generar una respuesta de error |
| | 7 | 275 | | return HandleException(ex); |
| | | 276 | | } |
| | 24 | 277 | | } |
| | | 278 | | |
| | | 279 | | // Métodos abstractos que deben ser implementados por las clases derivadas |
| | | 280 | | |
| | | 281 | | /// <summary> |
| | | 282 | | /// ACTualiza las propiedades de una entidad existente con los valores de una nueva entidad. |
| | | 283 | | /// </summary> |
| | | 284 | | /// <param name="existingEntity">La entidad existente que se va a actualizar.</param> |
| | | 285 | | /// <param name="request">La entidad con los nuevos valores.</param> |
| | | 286 | | /// <returns>La entidad actualizada.</returns> |
| | | 287 | | protected abstract TEntity UpdateProperties(TEntity existingEntity, TRequest request); |
| | | 288 | | |
| | | 289 | | /// <summary> |
| | | 290 | | /// Verifica si una entidad es válida. |
| | | 291 | | /// </summary> |
| | | 292 | | /// <param name="entity">La entidad que se va a validar.</param> |
| | | 293 | | /// <returns>True si la entidad es válida, de lo contrario False.</returns> |
| | | 294 | | protected abstract bool IsValid(TEntity entity); |
| | | 295 | | } |
| | | 296 | | } |