Veikedo

Untitled

Dec 28th, 2020
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.43 KB | None | 0 0
  1. /*
  2. message Pagination {
  3.   string pageToken = 1;
  4.   int32 pageSize = 2;
  5. }
  6. */
  7.  
  8.   public static class Extensions
  9.   {
  10.     public static async Task<PagedResponse<T>> ToPagedResponseAsync<T>(this IQueryable<T> source, Pagination pagination)
  11.     {
  12.       if (source == null)
  13.       {
  14.         throw new ArgumentNullException(nameof(source));
  15.       }
  16.  
  17.       pagination ??= new Pagination {PageSize = 10};
  18.  
  19.       var totalCount = await source.CountAsync();
  20.       var skip = GetSkip();
  21.  
  22.       var items = await source
  23.         .Skip(skip)
  24.         .Take(pagination.PageSize)
  25.         .ToListAsync();
  26.  
  27.       return new PagedResponse<T>
  28.       {
  29.         Items = items,
  30.         NextPageToken = GetNextPageToken()
  31.       };
  32.  
  33.       int GetSkip()
  34.       {
  35.         if (string.IsNullOrEmpty(pagination.PageToken))
  36.         {
  37.           return 0;
  38.         }
  39.  
  40.         try
  41.         {
  42.           var bytes = Convert.FromBase64String(pagination.PageToken);
  43.           return BitConverter.ToInt32(bytes);
  44.         }
  45.         catch (Exception e)
  46.         {
  47.           throw new ArgumentException("Could not decode page token", e);
  48.         }
  49.       }
  50.  
  51.       string GetNextPageToken()
  52.       {
  53.         var nextSkip = skip + pagination.PageSize;
  54.  
  55.         if (nextSkip >= totalCount)
  56.         {
  57.           return string.Empty;
  58.         }
  59.  
  60.         var bytes = BitConverter.GetBytes(nextSkip);
  61.         return Convert.ToBase64String(bytes);
  62.       }
  63.     }
  64.   }
  65.  
Add Comment
Please, Sign In to add comment