/
Frozin
/
DIS-3
Обзор
Документация
Войти
/
Frozin
/
DIS-3
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
API_PIR/Controllers/V2/NotesController.cs
149 строк
5 KB
Dobryk
Добавлены опциональные поля
20 окт 2025, 03:37
20 окт 2025, 03:37
29d65b9
Код
Авторство
О чём код?
using API_PIR.Extensions; using Microsoft.AspNetCore.Mvc; using API_PIR.Interfaces; using API_PIR.Models; namespace API_PIR.Controllers.V2; [ApiController] [ApiVersion("2.0")] [Route("api/v{version:apiVersion}/[controller]/[action]")] public class NotesController : ControllerBase { private readonly INoteService _noteService; public NotesController(INoteService noteService) { _noteService = noteService; } [HttpGet] public async Task<ActionResult<PaginatedList<NoteModel>>> GetNotes( [FromQuery] Guid? author, [FromQuery] PaginationParameters paginationParameters, [FromQuery] string? fields = null) { var notes = await _noteService.GetAllNotesAsync(); if (author is not null) { notes = notes.Where(n => n.Author == author); } var response = notes .ToPaginatedList(paginationParameters.PageNumber, paginationParameters.PageSize); if (string.IsNullOrEmpty(fields)) return Ok(response); var selectedFields = fields.Split(',', StringSplitOptions.RemoveEmptyEntries) .Select(f => f.Trim().ToLower()) .ToHashSet(); var result = response; result.Items = response.Items.Select(note => new NoteModel { Id = note.Id, Title = selectedFields.Contains("title") ? note.Title : "", Text = selectedFields.Contains("text") ? note.Text : "", CreatedAt = note.CreatedAt, Author = selectedFields.Contains("author") ? note.Author : Guid.Empty }); return Ok(result); } [HttpGet("{id:guid}")] public async Task<ActionResult<NoteModel>> GetNote(Guid id, [FromQuery] string? fields = null) { var note = await _noteService.GetNoteByIdAsync(id); if (note == null) { return NotFound(new { Message = $"Note with ID {id} not found" }); } if (string.IsNullOrEmpty(fields)) return Ok(note); var selectedFields = fields.Split(',', StringSplitOptions.RemoveEmptyEntries) .Select(f => f.Trim().ToLower()) .ToHashSet(); var response = new NoteModel { Id = note.Id, Title = selectedFields.Contains("title") ? note.Title : "", Text = selectedFields.Contains("text") ? note.Text : "", CreatedAt = note.CreatedAt, Author = selectedFields.Contains("author") ? note.Author : Guid.Empty }; return Ok(response); } [HttpPost] public async Task<ActionResult<NoteModel>> CreateNote([FromBody] NoteModel note, [FromHeader(Name = "Idempotency-Key")] Guid? idempotencyKey = null) { var createdNote = await _noteService.CreateNoteAsync(note); return CreatedAtAction(nameof(GetNote), new { id = createdNote.Id }, createdNote); } [HttpPut("{id:guid}")] public async Task<ActionResult<NoteModel>> UpdateNote(Guid id, [FromBody] NoteModel note) { var updatedNote = await _noteService.UpdateNoteAsync(id, note); if (updatedNote == null) { return NotFound(new { Message = $"Note with ID {id} not found" }); } return Ok(updatedNote); } [HttpPatch("{id:guid}")] public async Task<ActionResult<NoteModel>> PartialUpdateNote(Guid id, [FromBody] Dictionary<string, object> updates) { var existingNote = await _noteService.GetNoteByIdAsync(id); if (existingNote == null) { return NotFound(new { Message = $"Note with ID {id} not found" }); } foreach (var update in updates) { var property = typeof(NoteModel).GetProperty(update.Key); if (property != null && property.CanWrite) { try { var convertedValue = UsersController.ConvertValue(update.Value, property.PropertyType); property.SetValue(existingNote, convertedValue); } catch (Exception ex) { return BadRequest(new { Message = $"Error updating property '{update.Key}': {ex.Message}" }); } } } var updatedNote = await _noteService.UpdateNoteAsync(id, existingNote); return Ok(updatedNote); } [HttpDelete("{id:guid}")] public async Task<ActionResult> DeleteNote(Guid id) { var result = await _noteService.DeleteNoteAsync(id); if (!result) { return NotFound(new { Message = $"Note with ID {id} not found" }); } return NoContent(); } }