dotnet-digital-ops/DigitalOps.CQRS/Queries/Client/ClientQuery.cs

61 lines
2.0 KiB
C#

using DigitalOps.Authority.Services;
using DigitalOps.Dal;
using Microsoft.EntityFrameworkCore;
using OpenHarbor.CQRS.DynamicQuery.Abstractions;
namespace DigitalOps.CQRS.Queries.Client;
public class ClientParams
{
public long OrganizationId { get; set; }
}
public class ClientItem
{
public long Id { get; set; }
public IEnumerable<long> OrganizationIds { get; set; }
public required string Name { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }
}
public class ClientQueryableProvider(MainDbContext dbContext, UserIdentityService userIdentityService): IQueryableProviderOverride<ClientItem>
{
public async Task<IQueryable<ClientItem>> GetQueryableAsync(object query, CancellationToken cancellationToken = default)
{
long? organizationId = null;
if (query is IDynamicQueryParams<ClientParams> dynamicQuery)
{
var queryParams = dynamicQuery.GetParams();
organizationId = queryParams?.OrganizationId;
}
if (organizationId is null)
{
// don't bother to call the database if organizationId is not set
return Enumerable.Empty<ClientItem>().AsQueryable();
}
var user = await userIdentityService.GetUserOrDefaultAsync(cancellationToken);
var queryable = dbContext.Clients
.AsNoTracking();
var result = dbContext.Clients
.AsNoTracking()
.Where(client => client.OrganizationClients.Any(organizationClient => organizationClient.OrganizationId == organizationId))
.Where(client =>
client.OrganizationClients.Any(organizationClient => organizationClient.Organization.OrganizationUsers.Any(organizationUser => organizationUser.UserId == user!.Id)))
.Select(client => new ClientItem
{
Id = client.Id,
OrganizationIds = client.OrganizationClients.Select(organizationClient => organizationClient.OrganizationId),
Name = client.Name,
CreatedAt = client.CreatedAt,
UpdatedAt = client.UpdatedAt
});
return result;
}
}