|
| 1 | +using System; |
| 2 | +using System.Collections; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Threading; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace HotChocolate.Types.Pagination |
| 8 | +{ |
| 9 | + public static class CursorPagingHelper |
| 10 | + { |
| 11 | + public delegate ValueTask<IReadOnlyList<IndexEdge<TEntity>>> |
| 12 | + ToIndexEdgesAsync<TSource, TEntity>( |
| 13 | + TSource source, |
| 14 | + int offset, |
| 15 | + CancellationToken cancellationToken); |
| 16 | + |
| 17 | + public delegate TSource ApplySkip<TSource>(TSource source, int skip); |
| 18 | + |
| 19 | + public delegate TSource ApplyTake<TSource>(TSource source, int take); |
| 20 | + |
| 21 | + public delegate ValueTask<int> CountAsync<TSource>( |
| 22 | + TSource source, |
| 23 | + CancellationToken cancellationToken); |
| 24 | + |
| 25 | + public static async ValueTask<Connection> ApplyPagination<TSource, TEntity>( |
| 26 | + TSource source, |
| 27 | + CursorPagingArguments arguments, |
| 28 | + ApplySkip<TSource> applySkip, |
| 29 | + ApplyTake<TSource> applyTake, |
| 30 | + ToIndexEdgesAsync<TSource, TEntity> toIndexEdgesAsync, |
| 31 | + CountAsync<TSource> countAsync, |
| 32 | + CancellationToken cancellationToken = default) |
| 33 | + { |
| 34 | + // We only need the maximal element count if no `before` counter is set and no `first` |
| 35 | + // argument is provided. |
| 36 | + var maxElementCount = int.MaxValue; |
| 37 | + if (arguments.Before is null && arguments.First is null) |
| 38 | + { |
| 39 | + var count = await countAsync(source, cancellationToken); |
| 40 | + maxElementCount = count; |
| 41 | + |
| 42 | + // in case we already know the total count, we override the countAsync parameter |
| 43 | + // so that we do not have to fetch the count twice |
| 44 | + countAsync = (_, _) => new ValueTask<int>(count); |
| 45 | + } |
| 46 | + |
| 47 | + Range range = SliceRange<TEntity>(arguments, maxElementCount); |
| 48 | + |
| 49 | + var skip = range.Start; |
| 50 | + var take = range.Count(); |
| 51 | + |
| 52 | + // we fetch one element more than we requested |
| 53 | + if (take != maxElementCount) |
| 54 | + { |
| 55 | + take++; |
| 56 | + } |
| 57 | + |
| 58 | + TSource slicedSource = source; |
| 59 | + if (skip != 0) |
| 60 | + { |
| 61 | + slicedSource = applySkip(source, skip); |
| 62 | + } |
| 63 | + |
| 64 | + if (take != maxElementCount) |
| 65 | + { |
| 66 | + slicedSource = applyTake(slicedSource, take); |
| 67 | + } |
| 68 | + |
| 69 | + IReadOnlyList<IndexEdge<TEntity>> selectedEdges = |
| 70 | + await toIndexEdgesAsync(slicedSource, skip, cancellationToken); |
| 71 | + |
| 72 | + bool moreItemsReturnedThanRequested = selectedEdges.Count > range.Count(); |
| 73 | + bool isSequenceFromStart = range.Start == 0; |
| 74 | + |
| 75 | + selectedEdges = new SkipLastCollection<IndexEdge<TEntity>>( |
| 76 | + selectedEdges, |
| 77 | + moreItemsReturnedThanRequested); |
| 78 | + |
| 79 | + ConnectionPageInfo pageInfo = |
| 80 | + CreatePageInfo(isSequenceFromStart, moreItemsReturnedThanRequested, selectedEdges); |
| 81 | + |
| 82 | + return new Connection<TEntity>( |
| 83 | + selectedEdges, |
| 84 | + pageInfo, |
| 85 | + async ct => await countAsync(source, ct)); |
| 86 | + } |
| 87 | + |
| 88 | + private static ConnectionPageInfo CreatePageInfo<TEntity>( |
| 89 | + bool isSequenceFromStart, |
| 90 | + bool moreItemsReturnedThanRequested, |
| 91 | + IReadOnlyList<IndexEdge<TEntity>> selectedEdges) |
| 92 | + { |
| 93 | + // We know that there is a next page if more items than requested are returned |
| 94 | + bool hasNextPage = moreItemsReturnedThanRequested; |
| 95 | + |
| 96 | + // There is a previous page if the sequence start is not 0. |
| 97 | + // If you point to index 2 of a empty list, we assume that there is a previous page |
| 98 | + bool hasPreviousPage = !isSequenceFromStart; |
| 99 | + |
| 100 | + IndexEdge<TEntity>? firstEdge = null; |
| 101 | + IndexEdge<TEntity>? lastEdge = null; |
| 102 | + |
| 103 | + if (selectedEdges.Count > 0) |
| 104 | + { |
| 105 | + firstEdge = selectedEdges[0]; |
| 106 | + lastEdge = selectedEdges[selectedEdges.Count - 1]; |
| 107 | + } |
| 108 | + |
| 109 | + return new ConnectionPageInfo( |
| 110 | + hasNextPage, |
| 111 | + hasPreviousPage, |
| 112 | + firstEdge?.Cursor, |
| 113 | + lastEdge?.Cursor); |
| 114 | + } |
| 115 | + |
| 116 | + private static Range SliceRange<TEntity>( |
| 117 | + CursorPagingArguments arguments, |
| 118 | + int maxElementCount) |
| 119 | + { |
| 120 | + // [SPEC] if after is set then remove all elements of edges before and including |
| 121 | + // afterEdge. |
| 122 | + // |
| 123 | + // The cursor is increased by one so that the index points to the element after |
| 124 | + var startIndex = arguments.After is { } a |
| 125 | + ? IndexEdge<TEntity>.DeserializeCursor(a) + 1 |
| 126 | + : 0; |
| 127 | + |
| 128 | + // [SPEC] if before is set then remove all elements of edges before and including |
| 129 | + // beforeEdge. |
| 130 | + int before = arguments.Before is { } b |
| 131 | + ? IndexEdge<TEntity>.DeserializeCursor(b) |
| 132 | + : maxElementCount; |
| 133 | + |
| 134 | + // if after is negative we have know how much of the offset was in the negative range. |
| 135 | + // The amount of positions that are in the negative range, have to be subtracted from |
| 136 | + // the take or we will fetch too many items. |
| 137 | + int startOffsetCorrection = 0; |
| 138 | + if (startIndex < 0) |
| 139 | + { |
| 140 | + startOffsetCorrection = Math.Abs(startIndex); |
| 141 | + startIndex = 0; |
| 142 | + } |
| 143 | + |
| 144 | + Range range = new(startIndex, before); |
| 145 | + |
| 146 | + //[SPEC] If first is less than 0 throw an error |
| 147 | + ValidateFirst(arguments, out int? first); |
| 148 | + if (first is { }) |
| 149 | + { |
| 150 | + first -= startOffsetCorrection; |
| 151 | + if (first < 0) |
| 152 | + { |
| 153 | + first = 0; |
| 154 | + } |
| 155 | + } |
| 156 | + |
| 157 | + //[SPEC] Slice edges to be of length first by removing edges from the end of edges. |
| 158 | + range.Take(first); |
| 159 | + |
| 160 | + //[SPEC] if last is less than 0 throw an error |
| 161 | + ValidateLast(arguments, out int? last); |
| 162 | + //[SPEC] Slice edges to be of length last by removing edges from the start of edges. |
| 163 | + range.TakeLast(last); |
| 164 | + |
| 165 | + return range; |
| 166 | + } |
| 167 | + |
| 168 | + private class SkipLastCollection<T> : IReadOnlyList<T> |
| 169 | + { |
| 170 | + private readonly IReadOnlyList<T> _items; |
| 171 | + private readonly bool _skipLast; |
| 172 | + |
| 173 | + public SkipLastCollection( |
| 174 | + IReadOnlyList<T> items, |
| 175 | + bool skipLast = false) |
| 176 | + { |
| 177 | + _items = items; |
| 178 | + _skipLast = skipLast; |
| 179 | + Count = _items.Count; |
| 180 | + |
| 181 | + if (skipLast && Count > 0) |
| 182 | + { |
| 183 | + Count--; |
| 184 | + } |
| 185 | + } |
| 186 | + |
| 187 | + public int Count { get; } |
| 188 | + |
| 189 | + public IEnumerator<T> GetEnumerator() |
| 190 | + { |
| 191 | + for (var i = 0; i < _items.Count; i++) |
| 192 | + { |
| 193 | + if (i == _items.Count - 1 && _skipLast) |
| 194 | + { |
| 195 | + break; |
| 196 | + } |
| 197 | + |
| 198 | + yield return _items[i]; |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| 203 | + |
| 204 | + public T this[int index] => _items[index]; |
| 205 | + } |
| 206 | + |
| 207 | + internal class Range |
| 208 | + { |
| 209 | + public Range(int start, int end) |
| 210 | + { |
| 211 | + Start = start; |
| 212 | + End = end; |
| 213 | + } |
| 214 | + |
| 215 | + public int Start { get; private set; } |
| 216 | + |
| 217 | + public int End { get; private set; } |
| 218 | + |
| 219 | + public int Count() |
| 220 | + { |
| 221 | + if (End < Start) |
| 222 | + { |
| 223 | + return 0; |
| 224 | + } |
| 225 | + |
| 226 | + return End - Start; |
| 227 | + } |
| 228 | + |
| 229 | + public void Take(int? first) |
| 230 | + { |
| 231 | + if (first is { }) |
| 232 | + { |
| 233 | + var end = Start + first.Value; |
| 234 | + if (End > end) |
| 235 | + { |
| 236 | + End = end; |
| 237 | + } |
| 238 | + } |
| 239 | + } |
| 240 | + |
| 241 | + public void TakeLast(int? last) |
| 242 | + { |
| 243 | + if (last is { }) |
| 244 | + { |
| 245 | + var start = End - last.Value; |
| 246 | + if (Start < start) |
| 247 | + { |
| 248 | + Start = start; |
| 249 | + } |
| 250 | + } |
| 251 | + } |
| 252 | + } |
| 253 | + |
| 254 | + private static void ValidateFirst( |
| 255 | + CursorPagingArguments arguments, |
| 256 | + out int? first) |
| 257 | + { |
| 258 | + if (arguments.First < 0) |
| 259 | + { |
| 260 | + throw new ArgumentOutOfRangeException(nameof(first)); |
| 261 | + } |
| 262 | + |
| 263 | + first = arguments.First; |
| 264 | + } |
| 265 | + |
| 266 | + private static void ValidateLast( |
| 267 | + CursorPagingArguments arguments, |
| 268 | + out int? last) |
| 269 | + { |
| 270 | + if (arguments.Last < 0) |
| 271 | + { |
| 272 | + throw new ArgumentOutOfRangeException(nameof(last)); |
| 273 | + } |
| 274 | + |
| 275 | + last = arguments.Last; |
| 276 | + } |
| 277 | + } |
| 278 | +} |
| 279 | + |
0 commit comments