Выполнениие лабораторной работы на 5, трек 2.
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
using System.Text;
|
||||
|
||||
namespace Messenger.Api.Services;
|
||||
|
||||
// Непрозрачный для клиента cursor keyset-пагинации: (created_at, id) последнего элемента страницы.
|
||||
// Привязан к ресурсу (scope): cursor от другого списка или чата отклоняется как 400.
|
||||
public static class Cursors
|
||||
{
|
||||
public const string Chats = "chats";
|
||||
|
||||
public static string Messages(Guid chatId) => $"messages/{chatId:D}";
|
||||
|
||||
public static string Encode(string scope, DateTimeOffset createdAt, Guid id) =>
|
||||
Convert.ToBase64String(Encoding.UTF8.GetBytes($"{scope}|{createdAt.UtcTicks}:{id:D}"));
|
||||
|
||||
// cursor == null — первая страница (успех, value == null). Любая ошибка формата или чужой scope — false.
|
||||
public static bool TryDecode(string? cursor, string scope, out (DateTimeOffset CreatedAt, Guid Id)? value)
|
||||
{
|
||||
value = null;
|
||||
if (cursor is null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (cursor.Length == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var decoded = new UTF8Encoding(false, throwOnInvalidBytes: true).GetString(Convert.FromBase64String(cursor));
|
||||
var scoped = decoded.Split('|', 2);
|
||||
if (scoped.Length != 2 || scoped[0] != scope)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var parts = scoped[1].Split(':', 2);
|
||||
if (parts.Length != 2 ||
|
||||
!long.TryParse(parts[0], out var ticks) ||
|
||||
ticks < DateTimeOffset.MinValue.UtcTicks || ticks > DateTimeOffset.MaxValue.UtcTicks ||
|
||||
!Guid.TryParse(parts[1], out var id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = (new DateTimeOffset(ticks, TimeSpan.Zero), id);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is FormatException or ArgumentException or DecoderFallbackException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user