-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCursor.cs
More file actions
65 lines (54 loc) · 1.88 KB
/
Cursor.cs
File metadata and controls
65 lines (54 loc) · 1.88 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Dapper.GraphQL.Test.GraphQL
{
public static class Cursor
{
public static T FromCursor<T>(string cursor)
{
if (string.IsNullOrEmpty(cursor))
{
return default;
}
string decodedValue;
try
{
decodedValue = Base64Decode(cursor);
}
catch (FormatException)
{
return default;
}
return (T)Convert.ChangeType(decodedValue, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T), CultureInfo.InvariantCulture);
}
public static (string firstCursor, string lastCursor) GetFirstAndLastCursor<TItem, TCursor>(
IEnumerable<TItem> enumerable,
Func<TItem, TCursor> getCursorProperty)
{
if (getCursorProperty == null)
{
throw new ArgumentNullException(nameof(getCursorProperty));
}
if (enumerable == null || enumerable.Count() == 0)
{
return (null, null);
}
var firstCursor = ToCursor(getCursorProperty(enumerable.First()));
var lastCursor = ToCursor(getCursorProperty(enumerable.Last()));
return (firstCursor, lastCursor);
}
public static string ToCursor<T>(T value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
return Base64Encode(value.ToString());
}
private static string Base64Decode(string value) => Encoding.UTF8.GetString(Convert.FromBase64String(value));
private static string Base64Encode(string value) => Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
}
}