meJevin / Cryptlex.Net

C# library for the Cryptlex Web API
MIT License
9 stars 1 forks source link

Suggestion: Auto paginate results #15

Closed dgvives closed 2 years ago

dgvives commented 2 years ago

Automatically handle pagination in the library when listing results.

This is a quick and dirty solution I did for my own needs, based on the existing consoleApp example. It may help you to get an idea:

public class ConsoleApp
{
    private static ICryptlexClient? _cryptlexClient;

    public static async Task Main()
    {
        Console.WriteLine("Hello, World!");

        var builder = new ConfigurationBuilder().AddJsonFile("local.settings.json");
        var configuration = builder.Build();

        var cryptlexClientSettings = new CryptlexClientSettings { AccessToken = configuration["Cryptlex_key"] };
        _cryptlexClient = CryptlexClientFactory.Create(cryptlexClientSettings);

        Console.WriteLine("Fetching licenses from cryptlex...\n");

        var licensesCount = 0;
        await foreach (var license in ListAutoPagingAsync(new ListLicensesData { limit = 100, expired = true }))
        {
            licensesCount++;
            Console.WriteLine($"{license.id} -> {license.expiresAt:yyyy-MM-dd}");
        }
        Console.WriteLine($"Read {licensesCount} licenses");
    }

    private static async IAsyncEnumerable<License> ListAutoPagingAsync(ListLicensesData listLicensesData)
    {
        var currentPage = 1;
        IEnumerable<License> licenses;
        do
        {
            listLicensesData.page = currentPage;
            licenses = await _cryptlexClient!.Licenses.ListAsync(listLicensesData);

            foreach (var license in licenses)
            {
                yield return license;
            }

            currentPage++;
        }
        while (licenses.Count() is > 0);
    }
}
meJevin commented 2 years ago

Pretty cool! Thanks for the idea, I'll be making some changes soon, this might be one of them 😉

meJevin commented 2 years ago

closed by #22