aboutsummaryrefslogtreecommitdiffstats
path: root/code/api/src/Utilities/PaginationOperationFilter.cs
blob: ad02a3d6ac699730ce375ade8a7eacc3388a1d28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using Microsoft.Extensions.Options;
using MR.AspNetCore.Pagination;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace IOL.GreatOffice.Api.Utilities;

public class PaginationOperationFilter : IOperationFilter
{
    private readonly PaginationOptions _paginationOptions;

    public PaginationOperationFilter(
        IOptions<PaginationOptions> paginationOptions) {
        _paginationOptions = paginationOptions.Value;
    }

    public void Apply(OpenApiOperation operation, OperationFilterContext context) {
        var boolSchema = context.SchemaGenerator.GenerateSchema(typeof(bool), context.SchemaRepository);
        var intSchema = context.SchemaGenerator.GenerateSchema(typeof(int), context.SchemaRepository);

        if (PaginationActionDetector.IsKeysetPaginationResultAction(context.MethodInfo, out _)) {
            CreateParameter(_paginationOptions.FirstQueryParameterName, "true if you want the first page", boolSchema);
            CreateParameter(_paginationOptions.BeforeQueryParameterName, "Id of the reference entity you want results before");
            CreateParameter(_paginationOptions.AfterQueryParameterName, "Id of the reference entity you want results after");
            CreateParameter(_paginationOptions.LastQueryParameterName, "true if you want the last page", boolSchema);
        } else if (PaginationActionDetector.IsOffsetPaginationResultAction(context.MethodInfo, out _)) {
            CreateParameter(_paginationOptions.PageQueryParameterName, "The page", intSchema);
        }

        void CreateParameter(string name, string description, OpenApiSchema schema = null) {
            operation.Parameters.Add(new OpenApiParameter {
                Required = false,
                In = ParameterLocation.Query,
                Name = name,
                Description = description,
                Schema = schema,
            });
        }
    }
}