forked from mtusi2026/mtusi2026lab2
52 lines
2.6 KiB
C#
52 lines
2.6 KiB
C#
using Messenger.Api.Contracts;
|
|
using Messenger.Api.Services;
|
|
using static Messenger.Api.Services.ApiSupport;
|
|
|
|
namespace Messenger.Api.Endpoints;
|
|
|
|
public static class UiEndpoints
|
|
{
|
|
// The required /api/v1 history stays ascending. The web client has a separate,
|
|
// optional route to open a large chat at its newest page and page backwards.
|
|
public static IEndpointRouteBuilder MapUiEndpoints(this IEndpointRouteBuilder app)
|
|
{
|
|
app.MapGet("/api/ui/chats/{chat_id}/members", async (
|
|
string chat_id, HttpContext context, SessionService sessions, ChatService chats, UserService users) =>
|
|
{
|
|
var (actor, _) = await sessions.AuthenticateAsync(context);
|
|
if (actor is null) return Unauthorized(context);
|
|
if (!Guid.TryParse(chat_id, out var chatId))
|
|
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
|
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
|
|
return ApiError(context, 404, "not_found", "Чат не найден");
|
|
return Results.Ok(new { items = await users.ListForChatAsync(chatId) });
|
|
});
|
|
|
|
app.MapGet("/api/ui/chats/{chat_id}/messages", async (
|
|
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
|
|
{
|
|
var (actor, _) = await sessions.AuthenticateAsync(context);
|
|
if (actor is null) return Unauthorized(context);
|
|
if (!Guid.TryParse(chat_id, out var chatId))
|
|
return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
|
if (await chats.FindForMemberAsync(chatId, actor.Id) is null)
|
|
return ApiError(context, 404, "not_found", "Чат не найден");
|
|
var (limit, limitError) = ParseLimit(context);
|
|
if (limitError is not null) return limitError;
|
|
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"recent-chat:{chatId}");
|
|
if (cursorError is not null) return cursorError;
|
|
|
|
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1, newestFirst: true);
|
|
string? nextCursor = null;
|
|
if (page.Count > limit)
|
|
{
|
|
var last = page[limit - 1];
|
|
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"recent-chat:{chatId}", last.CreatedAt, last.Id));
|
|
page = page.Take(limit).ToList();
|
|
}
|
|
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
|
});
|
|
return app;
|
|
}
|
|
}
|