/
zykovad
/
PIR_Lab1_E-Library
Обзор
Документация
Войти
/
zykovad
/
PIR_Lab1_E-Library
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Controllers/v2/BookController.cs
165 строк
8 KB
Darya
Done lab 2
17 окт 2025, 22:38
17 окт 2025, 22:38
38ce9ac
Код
Авторство
О чём код?
using libraryAPI.DataStorage.v2; using libraryAPI.DTO; using libraryAPI.Entities.v2; using Microsoft.AspNetCore.Mvc; using Swashbuckle.AspNetCore.Annotations; namespace libraryAPI.Controllers.v2 { [ApiController] [ApiVersion("2.0")] [Route("api/v{version:apiVersion}/[controller]")] public class BooksController : ControllerBase { private readonly Data _data; public BooksController(Data data) { _data = data; } [HttpGet] [SwaggerOperation(Summary = "Получить список всех книг (с пагинацией)", Description = "Можно выбрать поля через параметр include (например: ?include=title,authors). Опциональные поля: tytle, isbn, genre, description, publicationyear, publisher, authors.", OperationId = "GetAllBooks")] [SwaggerResponse(200, "Список книг успешно получен", typeof(PagedResult<Book_Response>))] public IResult GetBooks(int page = 1, int pageSize = 10, [FromQuery] string? include = null) { // Преобразуем строку include в список var includeFields = include?.Split(',').Select(f => f.Trim().ToLower()).ToHashSet() ?? new HashSet<string>(); var list = _data.Books.ToList(); var total = list.Count; var items = list.Skip((page - 1) * pageSize).Take(pageSize) .Select(b => new Book_Response { Id = b.Id, Title = includeFields.Count == 0 || includeFields.Contains("title") ? b.Title : null, ISBN = includeFields.Count == 0 || includeFields.Contains("isbn") ? b.ISBN : null, Genre = includeFields.Count == 0 || includeFields.Contains("genre") ? b.Genre : null, Description = includeFields.Count == 0 || includeFields.Contains("description") ? b.Description : null, PublicationYear = includeFields.Count == 0 || includeFields.Contains("publicationyear") ? b.PublicationYear : 0, Publisher = includeFields.Count == 0 || includeFields.Contains("publisher") ? b.Publisher : null, Authors = includeFields.Count == 0 || includeFields.Contains("authors") ? b.AuthorBooks.Select(ab => $"{ab.Author.Surname} {ab.Author.Name}").ToList() : null }).ToList(); var response = new PagedResult<Book_Response> { Items = items, Page = page, PageSize = pageSize, TotalCount = total }; return Results.Json(response); } [HttpGet("{id}")] [SwaggerOperation(Summary = "Получить книгу по id", Description = "Можно выбрать поля через параметр include (например: ?include=title,authors). Опциональные поля: tytle, isbn, genre, description, publicationyear, publisher, authors.", OperationId = "GetBookById")] [SwaggerResponse(200, "Книга найдена", typeof(Book_Response))] public IResult GetBook(int id, [FromQuery] string? include = null) { // Преобразуем строку include в список var includeFields = include?.Split(',').Select(f => f.Trim().ToLower()).ToHashSet() ?? new HashSet<string>(); var book = _data.Books.FirstOrDefault(b => b.Id == id); if (book == null) return Results.NotFound(); var dto = new Book_Response { Id = book.Id, Title = includeFields.Count == 0 || includeFields.Contains("title") ? book.Title : null, ISBN = includeFields.Count == 0 || includeFields.Contains("isbn") ? book.ISBN : null, Genre = includeFields.Count == 0 || includeFields.Contains("genre") ? book.Genre : null, Description = includeFields.Count == 0 || includeFields.Contains("description") ? book.Description : null, PublicationYear = includeFields.Count == 0 || includeFields.Contains("publicationyear") ? book.PublicationYear : 0, Publisher = includeFields.Count == 0 || includeFields.Contains("publisher") ? book.Publisher : null, Authors = includeFields.Count == 0 || includeFields.Contains("authors") ? book.AuthorBooks.Select(ab => $"{ab.Author.Surname} {ab.Author.Name}").ToList() : null }; return Results.Json(dto); } [HttpPost] [SwaggerOperation(Summary = "Создать книгу", OperationId = "CreateBook")] [SwaggerResponse(200, "Книга успешно создана", typeof(Book_Response))] public IResult CreateBook(Book_Request dto, [FromHeader(Name = "Idempotency-Key")] string idempotencyKey) { if (string.IsNullOrEmpty(idempotencyKey)) return Results.BadRequest("Missing Idempotency-Key header."); if (_data.IdempotencyCache.ContainsKey(idempotencyKey)) return Results.Json(_data.IdempotencyCache[idempotencyKey]); var book = new Book { Id = _data.Books.Max(b => b.Id) + 1, Title = dto.Title, ISBN = dto.ISBN, Genre = dto.Genre, Description = dto.Description, PublicationYear = dto.PublicationYear, Publisher = dto.Publisher }; _data.Books.Add(book); _data.IdempotencyCache[idempotencyKey] = book; var response = new Book_Response { Id = book.Id, Title = book.Title, ISBN = book.ISBN, Genre = book.Genre, Description = book.Description, PublicationYear = book.PublicationYear, Publisher = book.Publisher, Authors = book.AuthorBooks.Select(ab => $"{ab.Author.Surname} {ab.Author.Name}").ToList() }; return Results.Json(response); } [HttpPut("{id}")] [SwaggerOperation(Summary = "Обновить книгу по id", OperationId = "UpdateBookById")] [SwaggerResponse(200, "Книга успешно обновлена", typeof(Book_Response))] public IResult UpdateBook(int id, Book_Request dto) { var book = _data.Books.FirstOrDefault(b => b.Id == id); if (book == null) return Results.NotFound(); book.Title = dto.Title; book.ISBN = dto.ISBN; book.Genre = dto.Genre; book.Description = dto.Description; book.PublicationYear = dto.PublicationYear; book.Publisher = dto.Publisher; var response = new Book_Response { Id = book.Id, Title = book.Title, ISBN = book.ISBN, Genre = book.Genre, Description = book.Description, PublicationYear = book.PublicationYear, Publisher = book.Publisher, Authors = book.AuthorBooks.Select(ab => $"{ab.Author.Surname} {ab.Author.Name}").ToList() }; return Results.Json(response); } [HttpDelete("{id}")] [SwaggerOperation(Summary = "Удалить книгу по id", OperationId = "DeleteBookById")] [SwaggerResponse(200, "Книга успешно удалена")] public IResult DeleteBook(int id) { var book = _data.Books.FirstOrDefault(b => b.Id == id); if (book == null) return Results.NotFound(); _data.Books.Remove(book); return Results.Ok($"Book with ID {id} deleted."); } } }