/// <summary>
 /// Adds offset pagination support to the field. Rewrites the type to a connection type and
 /// registers the mongo pagination handler
 /// </summary>
 /// <param name="descriptor">The descriptor of the field</param>
 /// <param name="type">
 /// The schema type of the entity. Not a connection type
 /// </param>
 /// <param name="entityType">The type of the entity</param>
 /// <param name="options">The options for pagination</param>
 /// <returns>The <paramref name="descriptor"/></returns>
 public static IObjectFieldDescriptor UseMongoDbOffsetPaging(
     this IObjectFieldDescriptor descriptor,
     Type?type             = null,
     Type?entityType       = null,
     PagingOptions options = default) =>
 descriptor.UseOffsetPaging(
     type,
     entityType,
     (services, sourceType) => services.GetService <MongoDbOffsetPagingProvider>() ??
     new MongoDbOffsetPagingProvider(),
     options);
    private static void ApplyConfigurationToFieldDescriptor <TEntity>(
        IObjectFieldDescriptor descriptor,
        Type?type,
        bool usePaging       = false,
        bool useOffsetPaging = false)
    {
        if (usePaging)
        {
            descriptor.UsePaging(nodeType: type ?? typeof(ObjectType <TEntity>));
        }

        if (useOffsetPaging)
        {
            descriptor.UseOffsetPaging(type ?? typeof(ObjectType <TEntity>));
        }

        descriptor
        .Use(
            next => async context =>
        {
            await next(context);

            if (context.Result is IQueryable <TEntity> queryable)
            {
                try
                {
                    context.ContextData["sql"] = queryable.ToQueryString();
                }
                catch (Exception ex)
                {
                    context.ContextData["sql"] = ex.Message;
                }

                context.Result = await queryable.ToListAsync();
            }

            if (context.Result is IExecutable executable)
            {
                try
                {
                    context.ContextData["sql"] = executable.Print();
                }
                catch (Exception ex)
                {
                    context.ContextData["sql"] = ex.Message;
                }
            }
        })
        .UseProjection()
        .UseFiltering()
        .UseSorting();
    }