68 lines
3.2 KiB
C#
68 lines
3.2 KiB
C#
using Messenger.Api.Contracts;
|
|
using Messenger.Api.Services;
|
|
using static Messenger.Api.Services.ApiSupport;
|
|
|
|
namespace Messenger.Api.Endpoints;
|
|
|
|
public static class ChatEndpoints
|
|
{
|
|
public static IEndpointRouteBuilder MapChatEndpoints(this IEndpointRouteBuilder app)
|
|
{
|
|
app.MapPost("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) =>
|
|
{
|
|
var (actor, _) = await sessions.AuthenticateAsync(context);
|
|
if (actor is null) return Unauthorized(context);
|
|
|
|
var (request, error) = await ReadJsonAsync<CreateChatRequest>(context);
|
|
if (error is not null) return error;
|
|
if (string.IsNullOrWhiteSpace(request!.Title) || request.Title.EnumerateRunes().Count() > 100)
|
|
return ApiError(context, 400, "invalid_request", "Некорректное название чата");
|
|
if (request.MemberIds is null || request.MemberIds.Count is < 1 or > 100 ||
|
|
request.MemberIds.Distinct().Count() != request.MemberIds.Count ||
|
|
!request.MemberIds.Contains(actor.Id))
|
|
return ApiError(context, 400, "invalid_request", "Некорректный список участников");
|
|
|
|
var chat = await chats.CreateAsync(request.Title, request.MemberIds);
|
|
return chat is null
|
|
? ApiError(context, 400, "invalid_request", "Один из участников не существует")
|
|
: Results.Json(chat, statusCode: StatusCodes.Status201Created);
|
|
});
|
|
|
|
app.MapGet("/api/v1/chats", async (HttpContext context, SessionService sessions, ChatService chats) =>
|
|
{
|
|
var (actor, _) = await sessions.AuthenticateAsync(context);
|
|
if (actor is null) return Unauthorized(context);
|
|
var (limit, limitError) = ParseLimit(context);
|
|
if (limitError is not null) return limitError;
|
|
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"user:{actor.Id}");
|
|
if (cursorError is not null) return cursorError;
|
|
|
|
var page = await chats.ListAsync(actor.Id, cursorTime, cursor?.Id, limit + 1);
|
|
string? nextCursor = null;
|
|
if (page.Count > limit)
|
|
{
|
|
var last = page[limit - 1];
|
|
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"user:{actor.Id}", last.CreatedAt, last.Id));
|
|
page = page.Take(limit).ToList();
|
|
}
|
|
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
|
});
|
|
|
|
app.MapGet("/api/v1/chats/{chat_id}", async (
|
|
string chat_id, HttpContext context, SessionService sessions, ChatService chats) =>
|
|
{
|
|
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");
|
|
|
|
var chat = await chats.FindForMemberAsync(chatId, actor.Id);
|
|
return chat is null
|
|
? ApiError(context, 404, "not_found", "Чат не найден")
|
|
: Results.Ok(chat);
|
|
});
|
|
|
|
return app;
|
|
}
|
|
}
|