Developer 02 5468d7b2aa feat: add QueryExtensions for filtering by Envelope and Receiver
- Introduced extension methods on IQueryable<TEntity> to filter entities
  by Envelope (Id or Uuid) and Receiver (Id, EmailAddress, or Signature).
- Throws BadRequestException if no valid identifier is provided when notnull = true.
- Improves query handling consistency across application layer.
2025-08-26 22:05:33 +02:00

64 lines
2.5 KiB
C#

using DigitalData.Core.Exceptions;
using EnvelopeGenerator.Application.Model;
using EnvelopeGenerator.Domain.Interfaces;
namespace EnvelopeGenerator.Application.Extensions;
/// <summary>
///
/// </summary>
public static class QueryExtensions
{
/// <summary>
///
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TEnvelopeQuery"></typeparam>
/// <param name="root"></param>
/// <param name="query"></param>
/// <param name="notnull"></param>
/// <returns></returns>
/// <exception cref="BadRequestException"></exception>
public static IQueryable<TEntity> Where<TEntity, TEnvelopeQuery>(this IQueryable<TEntity> root, IHasEnvelopeQuery<TEnvelopeQuery> query, bool notnull = true)
where TEntity : IHasEnvelope where TEnvelopeQuery : EnvelopeQueryBase
{
if (query.Envelope.Id is not null)
root = root.Where(e => e.Envelope!.Id == query.Envelope.Id);
else if (query.Envelope.Uuid is not null)
root = root.Where(e => e.Envelope!.Uuid == query.Envelope.Uuid);
else if (notnull)
throw new BadRequestException(
"Either Envelope Id or Envelope Uuid must be provided in the query."
);
return root;
}
/// <summary>
///
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <typeparam name="TReceiverQueryBase"></typeparam>
/// <param name="root"></param>
/// <param name="query"></param>
/// <param name="notnull"></param>
/// <returns></returns>
/// <exception cref="BadRequestException"></exception>
public static IQueryable<TEntity> Where<TEntity, TReceiverQueryBase>(this IQueryable<TEntity> root, IHasReceiverQuery<TReceiverQueryBase> query, bool notnull = true)
where TEntity : IHasReceiver where TReceiverQueryBase : ReceiverQueryBase
{
if (query.Receiver.Id is not null)
root = root.Where(e => e.Receiver!.Id == query.Receiver.Id);
else if (query.Receiver.EmailAddress is not null)
root = root.Where(e => e.Receiver!.EmailAddress == query.Receiver.EmailAddress);
else if (query.Receiver.Signature is not null)
root = root.Where(e => e.Receiver!.Signature == query.Receiver.Signature);
else if (notnull)
throw new BadRequestException(
"Receiver must have at least one identifier (Id, EmailAddress, or Signature)."
);
return root;
}
}