Add stable inbox cursor pagination
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
using System.Text;
|
||||
namespace GuestOps.Web;
|
||||
|
||||
public sealed record ConversationPage(IReadOnlyList<Conversation> Items,string? NextCursor);
|
||||
public static class ConversationPaging
|
||||
{
|
||||
public static string Encode(Conversation item)=>Convert.ToBase64String(Encoding.UTF8.GetBytes(item.ReceivedAt.Ticks+"|"+item.Id)).TrimEnd('=').Replace('+','-').Replace('/','_');
|
||||
public static bool TryDecode(string? value,out DateTime at,out string id)
|
||||
{
|
||||
at=default;id="";if(string.IsNullOrEmpty(value))return true;
|
||||
try
|
||||
{
|
||||
if(value.Length>160)return false;var raw=value.Replace('-','+').Replace('_','/');raw=raw.PadRight((raw.Length+3)/4*4,'=');
|
||||
var parts=Encoding.UTF8.GetString(Convert.FromBase64String(raw)).Split('|');
|
||||
return parts.Length==2&&long.TryParse(parts[0],out var ticks)&&ticks>=DateTime.MinValue.Ticks&&ticks<=DateTime.MaxValue.Ticks&&System.Text.RegularExpressions.Regex.IsMatch(parts[1],"^[a-f0-9]{32}$")&&(at=new DateTime(ticks,DateTimeKind.Utc))!=default&&(id=parts[1]).Length>0;
|
||||
}
|
||||
catch{return false;}
|
||||
}
|
||||
}
|
||||
@@ -169,6 +169,7 @@ api.MapPut("/hotel", async (SettingsInput input, HttpContext c) =>
|
||||
await Session.Audit(store, c, "Updated hotel settings"); return Results.Ok(hotel);
|
||||
}).RequireAuthorization("Owner");
|
||||
api.MapGet("/conversations", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List<Conversation>(Session.Hotel(c))).OrderByDescending(x => x.ReceivedAt)));
|
||||
api.MapGet("/conversations/page",async(string? cursor,HttpContext c)=>ConversationPaging.TryDecode(cursor,out var before,out var beforeId)?Results.Ok(await store.ConversationPage(Session.Hotel(c),cursor==null?null:before,beforeId,50)):Results.BadRequest(new{error="Invalid conversation cursor."}));
|
||||
api.MapGet("/conversations/{id}", async (string id, HttpContext c) => await store.Get<Conversation>(Session.Hotel(c), id) is { } item ? Results.Ok(item) : Results.NotFound());
|
||||
api.MapPut("/conversations/{id}/draft", async (string id, DraftInput input, HttpContext c) =>
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@ public interface IStore
|
||||
Task<DateTime?> WorkerLastSeen();
|
||||
Task RecordWorkerHeartbeat();
|
||||
Task<List<T>> List<T>(string hotel) where T : TenantDocument;
|
||||
Task<ConversationPage> ConversationPage(string hotel,DateTime? before,string beforeId,int limit);
|
||||
Task<T?> Get<T>(string hotel, string id) where T : TenantDocument;
|
||||
Task Insert<T>(T document) where T : TenantDocument;
|
||||
Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument;
|
||||
@@ -78,6 +79,12 @@ public sealed class MongoStore : IStore
|
||||
if (typeof(T) == typeof(PmsChange) || typeof(T) == typeof(PaymentRequest)) query = query.Sort(Builders<T>.Sort.Descending("UpdatedAt"));
|
||||
return query.Limit(500).ToListAsync();
|
||||
}
|
||||
public async Task<ConversationPage> ConversationPage(string hotel,DateTime? before,string beforeId,int limit)
|
||||
{
|
||||
var filter=Scope<Conversation>(hotel);if(before!=null)filter&=Builders<Conversation>.Filter.Lt(x=>x.ReceivedAt,before.Value)|(Builders<Conversation>.Filter.Eq(x=>x.ReceivedAt,before.Value)&Builders<Conversation>.Filter.Lt(x=>x.Id,beforeId));
|
||||
var rows=await Collection<Conversation>().Find(filter).SortByDescending(x=>x.ReceivedAt).ThenByDescending(x=>x.Id).Limit(limit+1).ToListAsync();
|
||||
var more=rows.Count>limit;if(more)rows.RemoveAt(rows.Count-1);return new(rows,more?ConversationPaging.Encode(rows[^1]):null);
|
||||
}
|
||||
public async Task<T?> Get<T>(string hotel, string id) where T : TenantDocument => await Collection<T>().Find(Scope<T>(hotel) & Builders<T>.Filter.Eq(x => x.Id, id)).FirstOrDefaultAsync();
|
||||
public Task Insert<T>(T document) where T : TenantDocument
|
||||
{
|
||||
@@ -179,6 +186,11 @@ public sealed class PreviewStore : IStore
|
||||
static string Json<T>(T value) => System.Text.Json.JsonSerializer.Serialize(value);
|
||||
public Task Initialize() => Task.CompletedTask;
|
||||
public Task<List<T>> List<T>(string hotel) where T : TenantDocument => Task.FromResult(rows.Where(x => x.Key.StartsWith(typeof(T).Name + ":")).Select(x => Clone<T>(x.Value)).Where(x => x.HotelId == hotel).ToList());
|
||||
public async Task<ConversationPage> ConversationPage(string hotel,DateTime? before,string beforeId,int limit)
|
||||
{
|
||||
var query=(await List<Conversation>(hotel)).OrderByDescending(x=>x.ReceivedAt).ThenByDescending(x=>x.Id).Where(x=>before==null||x.ReceivedAt<before||x.ReceivedAt==before&&string.CompareOrdinal(x.Id,beforeId)<0).Take(limit+1).ToList();
|
||||
var more=query.Count>limit;if(more)query.RemoveAt(query.Count-1);return new(query,more?ConversationPaging.Encode(query[^1]):null);
|
||||
}
|
||||
public async Task<T?> Get<T>(string hotel, string id) where T : TenantDocument => (await List<T>(hotel)).SingleOrDefault(x => x.Id == id);
|
||||
public Task Insert<T>(T document) where T : TenantDocument { if (!rows.TryAdd(Key<T>(document.Id), Json(document))) throw new InvalidOperationException("Duplicate document"); return Task.CompletedTask; }
|
||||
public Task<bool> Replace<T>(string hotel, string id, long version, T document) where T : TenantDocument
|
||||
|
||||
Reference in New Issue
Block a user