Українська
Групи кінцевих точок
Крок 1. Один файл на область
Навіщо. Кожна область API – власний профіль, інші користувачі, чати, повідомлення – отримує один статичний клас із методом Map…Endpoints і одним невеликим закритим методом на кожну кінцеву точку. Група маршрутів (MapGroup("/chats")) дає всім своїм кінцевим точкам спільний префікс, тег для OpenAPI і згодом спільні правила, наприклад обмеження частоти запитів. Тоді файл читається як таблиця маршрутів угорі, за якою йдуть реалізації.
Кінцеві точки аватарів і вкладень потребують роботи з файлами; вони з’являться в темі 13. Усе інше зіставляємо зараз.
Крок 2. Профіль і користувачі
Що зробити.
cs
using System.Security.Claims;
using Chatex.Api.Infrastructure;
using Chatex.Core.Users;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
/// <summary>The signed-in user's own account under <c>/api/me</c>.</summary>
internal static class ProfileEndpoints
{
public static void MapProfileEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/me").WithTags("Profile");
group.MapGet("", GetAsync).WithName("GetMyProfile");
group.MapPut("", UpdateAsync).WithName("UpdateMyProfile");
group.MapPut("/password", ChangePasswordAsync).WithName("ChangePassword")
.WithSummary("Changes the password and ends every session, this one included.");
}
private static async Task<Results<Ok<MyProfileDto>, ProblemHttpResult>> GetAsync(
ClaimsPrincipal user, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.GetMyProfileAsync(user.GetUserId(), cancellationToken)).ToOk();
private static async Task<Results<Ok<MyProfileDto>, ProblemHttpResult>> UpdateAsync(
UpdateProfileCommand command, ClaimsPrincipal user, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.UpdateProfileAsync(user.GetUserId(), command, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> ChangePasswordAsync(
ChangePasswordCommand command, ClaimsPrincipal user, IProfileService profiles, HttpResponse response,
CancellationToken cancellationToken)
{
var result = await profiles.ChangePasswordAsync(user.GetUserId(), command, cancellationToken);
if (result.IsSuccess)
{
RefreshTokenCookie.Clear(response);
}
return result.ToNoContent();
}
}Власний профіль міститься за адресою /api/me: клієнтові ніколи не доводиться знати власний ідентифікатор. Зміна пароля завершує всі сесії (тема 9), зокрема й сесію цього браузера, тому кінцева точка також очищає cookie оновлення.
cs
using Chatex.Api.Infrastructure;
using Chatex.Core.Users;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class UserEndpoints
{
public static void MapUserEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/users").WithTags("Users");
group.MapGet("", SearchAsync).WithName("SearchUsers")
.WithSummary("Finds users by user name or display name (at least 2 characters).");
group.MapGet("/{id:guid}", GetAsync).WithName("GetUser");
}
private static async Task<Results<Ok<UserSummaryDto[]>, ProblemHttpResult>> SearchAsync(
string? query, int? limit, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.SearchUsersAsync(query ?? "", limit, cancellationToken)).ToOk();
private static async Task<Results<Ok<UserDto>, ProblemHttpResult>> GetAsync(
Guid id, IProfileService profiles, CancellationToken cancellationToken) =>
(await profiles.GetUserAsync(id, cancellationToken)).ToOk();
}Обмеження маршруту: {id:guid} відповідає лише GUID. Запит /api/users/abc узагалі не потрапляє до кінцевої точки й отримує відповідь 404.
Крок 3. Чати
Що зробити.
cs
using System.Security.Claims;
using Chatex.Api.Contracts;
using Chatex.Api.Infrastructure;
using Chatex.Core.Chats;
using Chatex.Core.Common;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class ChatEndpoints
{
public static void MapChatEndpoints(this IEndpointRouteBuilder routes)
{
var group = routes.MapGroup("/chats").WithTags("Chats");
group.MapGet("", GetMyChatsAsync).WithName("GetMyChats")
.WithSummary("The caller's chats, most recently active first.");
group.MapPost("", CreateAsync).WithName("CreateChat").WithSummary("Creates a group or channel.");
group.MapPost("/direct", OpenDirectAsync).WithName("OpenDirectChat")
.WithSummary("Returns the direct chat with a user, creating it on first use.");
group.MapGet("/search", SearchAsync).WithName("SearchPublicChats");
group.MapGet("/{id:guid}", GetAsync).WithName("GetChat");
group.MapPut("/{id:guid}", UpdateAsync).WithName("UpdateChat");
group.MapDelete("/{id:guid}", DeleteAsync).WithName("DeleteChat");
group.MapPost("/{id:guid}/join", JoinAsync).WithName("JoinChat");
group.MapPost("/{id:guid}/leave", LeaveAsync).WithName("LeaveChat");
group.MapGet("/{id:guid}/members", GetMembersAsync).WithName("GetChatMembers");
group.MapPost("/{id:guid}/members", AddMembersAsync).WithName("AddChatMembers");
group.MapDelete("/{id:guid}/members/{userId:guid}", RemoveMemberAsync).WithName("RemoveChatMember");
group.MapPut("/{id:guid}/members/{userId:guid}/role", ChangeRoleAsync).WithName("ChangeChatMemberRole")
.WithSummary("Owner only. Making someone the owner transfers ownership.");
group.MapPut("/{id:guid}/mute", SetMutedAsync).WithName("SetChatMuted");
group.MapPost("/{id:guid}/read", MarkReadAsync).WithName("MarkChatRead")
.WithSummary("Moves the caller's read position forward to a message.");
}
private static async Task<Results<Ok<PageDto<ChatListItemDto>>, ProblemHttpResult>> GetMyChatsAsync(
string? cursor, int? limit, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.GetMyChatsAsync(user.GetUserId(), cursor, limit, cancellationToken)).ToOk();
private static async Task<Results<Created<ChatDto>, ProblemHttpResult>> CreateAsync(
CreateChatCommand command, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.CreateAsync(user.GetUserId(), command, cancellationToken)).ToCreated(c => $"/api/chats/{c.Id}");
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> OpenDirectAsync(
OpenDirectRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.OpenDirectAsync(user.GetUserId(), request.UserId, cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatSummaryDto[]>, ProblemHttpResult>> SearchAsync(
string? query, int? limit, IChatService chats, CancellationToken cancellationToken) =>
(await chats.SearchPublicAsync(query ?? "", limit, cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> GetAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.GetAsync(user.GetUserId(), id, cancellationToken)).ToOk();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> UpdateAsync(
Guid id, UpdateChatCommand command, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.UpdateAsync(user.GetUserId(), id, command, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> DeleteAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.DeleteAsync(user.GetUserId(), id, cancellationToken)).ToNoContent();
private static async Task<Results<Ok<ChatDto>, ProblemHttpResult>> JoinAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.JoinAsync(user.GetUserId(), id, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> LeaveAsync(
Guid id, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.LeaveAsync(user.GetUserId(), id, cancellationToken)).ToNoContent();
private static async Task<Results<Ok<PageDto<ChatMemberDto>>, ProblemHttpResult>> GetMembersAsync(
Guid id, string? cursor, int? limit, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.GetMembersAsync(user.GetUserId(), id, cursor, limit, cancellationToken)).ToOk();
private static async Task<Results<Ok<AddMembersResponse>, ProblemHttpResult>> AddMembersAsync(
Guid id, AddMembersRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken)
{
var result = await chats.AddMembersAsync(user.GetUserId(), id, request.UserIds ?? [], cancellationToken);
return result.IsSuccess ? TypedResults.Ok(new AddMembersResponse(result.Value)) : result.Error.ToProblem();
}
private static async Task<Results<NoContent, ProblemHttpResult>> RemoveMemberAsync(
Guid id, Guid userId, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.RemoveMemberAsync(user.GetUserId(), id, userId, cancellationToken)).ToNoContent();
private static async Task<Results<NoContent, ProblemHttpResult>> ChangeRoleAsync(
Guid id, Guid userId, ChangeRoleRequest request, ClaimsPrincipal user, IChatService chats,
CancellationToken cancellationToken) =>
(await chats.ChangeRoleAsync(user.GetUserId(), id, userId, request.Role, cancellationToken)).ToNoContent();
private static async Task<Results<NoContent, ProblemHttpResult>> SetMutedAsync(
Guid id, SetMutedRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.SetMutedAsync(user.GetUserId(), id, request.Muted, cancellationToken)).ToNoContent();
private static async Task<Results<NoContent, ProblemHttpResult>> MarkReadAsync(
Guid id, MarkReadRequest request, ClaimsPrincipal user, IChatService chats, CancellationToken cancellationToken) =>
(await chats.MarkReadAsync(user.GetUserId(), id, request.MessageId, cancellationToken)).ToNoContent();
}- Маршрути в стилі REST: колекція
/api/chats(GETповертає список,POSTстворює), один чат/api/chats/{id}(GET,PUT,DELETE), підресурси на кшталт/membersі/members/{userId}/role. Дії, що не є простим читанням чи записом, стаютьPOSTна дієслово:/join,/leave,/read. /directі/searchоголошено перед/{id:guid}; обмеження все одно розрізняє їх.- Параметри запиту, як-от
string? cursor, int? limit, зв’язуються з рядка запиту за іменем:GET /api/chats?limit=20&cursor=…. CreateAsyncвідповідає201 Createdіз заголовкомLocation, що вказує на новий чат.AddMembersAsyncобгортає число вAddMembersResponse, тож тіло є об’єктом:{ "added": 2 }.
Крок 4. Повідомлення
Що зробити.
cs
using System.Security.Claims;
using Chatex.Api.Infrastructure;
using Chatex.Core.Common;
using Chatex.Core.Messages;
using Microsoft.AspNetCore.Http.HttpResults;
namespace Chatex.Api.Endpoints;
internal static class MessageEndpoints
{
public static void MapMessageEndpoints(this IEndpointRouteBuilder routes)
{
var history = routes.MapGroup("/chats/{chatId:guid}/messages").WithTags("Messages");
history.MapGet("", GetHistoryAsync).WithName("GetMessages")
.WithSummary("A page of history: newest first, `before` for older pages, `after` to catch up (oldest first).");
history.MapPost("", SendAsync).WithName("SendMessage");
var messages = routes.MapGroup("/messages").WithTags("Messages");
messages.MapPut("/{id:guid}", EditAsync).WithName("EditMessage").WithSummary("Only the sender can edit.");
messages.MapDelete("/{id:guid}", DeleteAsync).WithName("DeleteMessage")
.WithSummary("The sender or a chat admin can delete; a placeholder stays.");
}
private static async Task<Results<Ok<PageDto<MessageDto>>, ProblemHttpResult>> GetHistoryAsync(
Guid chatId, string? before, string? after, int? limit, ClaimsPrincipal user, IMessageService messages,
CancellationToken cancellationToken) =>
(await messages.GetHistoryAsync(user.GetUserId(), chatId, before, after, limit, cancellationToken)).ToOk();
private static async Task<Results<Created<MessageDto>, ProblemHttpResult>> SendAsync(
Guid chatId, SendMessageCommand command, ClaimsPrincipal user, IMessageService messages,
CancellationToken cancellationToken) =>
(await messages.SendAsync(user.GetUserId(), chatId, command, cancellationToken)).ToCreated(_ => null);
private static async Task<Results<Ok<MessageDto>, ProblemHttpResult>> EditAsync(
Guid id, EditMessageCommand command, ClaimsPrincipal user, IMessageService messages, CancellationToken cancellationToken) =>
(await messages.EditAsync(user.GetUserId(), id, command, cancellationToken)).ToOk();
private static async Task<Results<NoContent, ProblemHttpResult>> DeleteAsync(
Guid id, ClaimsPrincipal user, IMessageService messages, CancellationToken cancellationToken) =>
(await messages.DeleteAsync(user.GetUserId(), id, cancellationToken)).ToNoContent();
}Дві групи в одному файлі: історія й надсилання належать чату (/api/chats/{chatId}/messages), а редагування й видалення адресують повідомлення безпосередньо (/api/messages/{id}), бо ідентифікатора повідомлення досить, щоб знайти його чат. Надіслане повідомлення відповідає 201 без Location – в окремого повідомлення немає власного GET; про це говорить ToCreated(_ => null).
Перевірка
dotnet build проходить успішно. Кінцеві точки готові, але ще не зіставлені: це робота Program.cs, далі.