Is there a way to implement global filters using the MongoDb integration for HotChocolate when all my types allow soft delete? Soft delete means marking the record to be deleted by setting the “IsDeleted” field to true, and then completely removing those records after a few weeks.
e.g.
public interface ISoftDelete
{
bool IsDeleted { get; set; }
}
public class ExampleModel : ISoftDelete
{
public string Id { get; set; }
public string Name { get; set; }
[GraphQLIgnore]
public bool IsDeleted { get; set; }
}
While all my types have the “IsDeleted” flag, it is ignored in the GraphQL schema. My question is, how can I set a global filter for all Find and Aggregation operations so that all queries made to MongoDB include the filter “IsDeleted = false”?
This way, customers will never see deleted records, and developers won’t need to manually add that filter to each query anymore.
Field middleware best fits for your purpose.
Definition:
public class SoftDeletedEntitiesFilter
{
private readonly FieldDelegate _next;
public SoftDeletedEntitiesFilter(FieldDelegate next)
{
_next = next;
}
public async Task InvokeAsync(IMiddlewareContext context)
{
await _next(context);
if (context.Result is IQueryable<ISoftDelete> deletableEntities)
{
context.Result = deletableEntities.Where(e => !e.IsDeleted);
}
}
}
Usage:
builder.Services
.AddGraphQLServer()
.UseField<SoftDeletedEntitiesFilter>()
.AddQueryType<Query>();
With this usage the filter middleware will be applied globally for every queried field, but the filter condition will only pass for fields that have resolvers like this:
public class Query
{
public IQueryable<ExampleModel> GetModels([Service] DbContext dbContext)
=> dbContext.Models;
}