/
egopen
/
Lab1
Обзор
Документация
Войти
/
egopen
/
Lab1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lab4/library/Controllers/v2/BooksController.cs
209 строк
7 KB
Egopen
lab 4
01 ноя 2025, 18:03
01 ноя 2025, 18:03
78d017c
Код
Авторство
О чём код?
using library.DB.Models; using library.DTO; using library.QueueMessages; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.OpenApi.Models; using RabbitMQ.Client; using System.Text; using System.Text.Json; namespace library.Controllers.v2 { [ApiController] [Route("api/v2/[controller]")] public class BooksController : ControllerBase { private readonly IChannel _channel; public BooksController(IConnection rabbitConnection) { _channel = rabbitConnection.CreateChannelAsync().GetAwaiter().GetResult(); } private string GetAuthToken() { var authHeader = Request.Headers["Authorization"].FirstOrDefault(); if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer ")) { throw new UnauthorizedAccessException("Authorization header is required"); } return authHeader.Substring("Bearer ".Length).Trim(); } [HttpGet("{bookId}")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetBook(Guid bookId) { var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v2", Action = "get_book", Data = new { BookId = bookId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "get_book.request",true, props, messageBytes); return Accepted(new { message = "Get book request sent", requestId = message.Id }); } [HttpGet] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> GetBooks([FromQuery] BooksQuery query) { var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v2", Action = "get_books", Data = new { Page = query.Page, PageSize = query.PageSize, AuthorId = query.AuthorId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "get_books.request", true, props, messageBytes); return Accepted(new { message = "Get books request sent", requestId = message.Id }); } [HttpPost] [Authorize(Roles = "Admin,Moderator")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> AddBook([FromBody] AddBookRequestV2 request) { if (!ModelState.IsValid) { return BadRequest(new { message = "Validation failed", errors = ModelState.Values .SelectMany(v => v.Errors) .Select(e => e.ErrorMessage) }); } var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v2", Action = "add_book", AuthKey = token, Data = new { request.AuthorId, request.Title, request.CreationDate } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "add_book.request", true, props, messageBytes); return Accepted(new { message = "Add book request sent", requestId = message.Id }); } [HttpDelete("{bookId}")] [Authorize(Roles = "Admin,Moderator")] [ProducesResponseType(typeof(object), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> DeleteBook(Guid bookId) { var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v2", Action = "delete_book", AuthKey = token, Data = new { BookId = bookId } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "delete_book.request", true, props, messageBytes); return Accepted(new { message = "Delete book request sent", requestId = message.Id }); } [HttpPatch("{bookId}")] [Authorize(Roles = "Admin,Moderator")] [ProducesResponseType(typeof(Book), 200)] [ProducesResponseType(typeof(OpenApiError), 404)] [ProducesResponseType(typeof(OpenApiError), 500)] public async Task<IActionResult> UpdateBook(Guid bookId, [FromBody] UpdateBookRequest request) { if (!ModelState.IsValid) { return BadRequest(new { message = "Validation failed", errors = ModelState.Values .SelectMany(v => v.Errors) .Select(e => e.ErrorMessage) }); } var token = GetAuthToken(); var message = new BaseMessage { Id = Guid.NewGuid(), Version = "v2", Action = "update_book", AuthKey = token, Data = new { BookId = bookId, Title = request.Title, AuthorId = request.AuthorId, CreationDate = request.CreationDate } }; var props = new BasicProperties(); props.ContentType = "application/json"; props.MessageId = message.Id.ToString(); var messageBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message)); await _channel.BasicPublishAsync("Books", "update_book.request", true, props, messageBytes); return Accepted(new { message = "Update book request sent", requestId = message.Id }); } } }