forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL, сессии, Redis и исследование
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
using Messenger.Api.Contracts;
|
||||
using Messenger.Api.Services;
|
||||
using static Messenger.Api.Services.ApiSupport;
|
||||
|
||||
namespace Messenger.Api.Endpoints;
|
||||
|
||||
public static class MessageEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapMessageEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapPost("/api/v1/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 (request, error) = await ReadJsonAsync<CreateMessageRequest>(context);
|
||||
if (error is not null) return error;
|
||||
if (string.IsNullOrWhiteSpace(request!.Text) || request.Text.EnumerateRunes().Count() > 4000)
|
||||
return ApiError(context, 400, "invalid_request", "Некорректный текст сообщения");
|
||||
|
||||
var message = await messages.CreateAsync(chatId, actor.Id, request.Text);
|
||||
return Results.Json(message, statusCode: StatusCodes.Status201Created);
|
||||
});
|
||||
|
||||
app.MapGet("/api/v1/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, $"chat:{chatId}");
|
||||
if (cursorError is not null) return cursorError;
|
||||
|
||||
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1);
|
||||
string? nextCursor = null;
|
||||
if (page.Count > limit)
|
||||
{
|
||||
var last = page[limit - 1];
|
||||
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"chat:{chatId}", last.CreatedAt, last.Id));
|
||||
page = page.Take(limit).ToList();
|
||||
}
|
||||
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user