/
ArtSerg
/
IntegrationProject
Обзор
Документация
Войти
/
ArtSerg
/
IntegrationProject
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
lab4
Integration1/Controllers/TasksV1Controller.cs
112 строк
4 KB
artS3rg
Добавлена Лабораторная №2: лимиты, пагинация, опциональные поля, внутренний API, Swagger обновлен
25 окт 2025, 10:49
25 окт 2025, 10:49
d03a63c
Код
Авторство
О чём код?
using Integration1.Data; using Integration1.Dtos; using Integration1.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; using Microsoft.EntityFrameworkCore; namespace Integration1.Controllers { [ApiController] [Route("api/v1/tasks")] [Authorize] public class TasksV1Controller : ControllerBase { private readonly AppDbContext _db; public TasksV1Controller(AppDbContext db) => _db = db; private string GetUserId() => User.FindFirst("UserId")?.Value ?? ""; [HttpGet] public async Task<IActionResult> GetTasks([FromQuery] int page = 1, [FromQuery] int pageSize = 10, [FromQuery] string? include = null) { if (page < 1) page = 1; if (pageSize < 1) pageSize = 10; if (pageSize > 100) pageSize = 100; var userId = GetUserId(); var q = _db.Tasks.Where(t => t.UserId == userId).AsNoTracking(); var total = await q.CountAsync(); var totalPages = (int)Math.Ceiling(total / (double)pageSize); var items = await q .OrderBy(t => t.Id) .Skip((page - 1) * pageSize) .Take(pageSize) .ToListAsync(); var projection = ProjectTasks(items, include); Response.Headers["X-Total-Count"] = total.ToString(); Response.Headers["X-Total-Pages"] = totalPages.ToString(); Response.Headers["X-Current-Page"] = page.ToString(); return Ok(new PagedResult<object> { Items = projection, TotalCount = total, Page = page, PageSize = pageSize }); } [HttpPost] public async Task<IActionResult> CreateTask([FromBody] TaskCreateDto dto) { var task = new TaskItem { Title = dto.Title, Description = dto.Description, Priority = dto.Priority, UserId = GetUserId() }; _db.Tasks.Add(task); await _db.SaveChangesAsync(); return CreatedAtAction(nameof(GetTasks), new { id = task.Id }, task); } [HttpPut("{id}")] public async Task<IActionResult> UpdateTask(int id, [FromBody] TaskUpdateDto dto) { var task = await _db.Tasks.FindAsync(id); if (task == null) return NotFound(); if (dto.Title != null) task.Title = dto.Title; if (dto.Description != null) task.Description = dto.Description; if (dto.Priority.HasValue) task.Priority = dto.Priority.Value; if (dto.IsCompleted.HasValue) task.IsCompleted = dto.IsCompleted.Value; await _db.SaveChangesAsync(); return Ok(task); } [HttpDelete("{id}")] public async Task<IActionResult> DeleteTask(int id) { var task = await _db.Tasks.FindAsync(id); if (task == null) return NotFound(); _db.Tasks.Remove(task); await _db.SaveChangesAsync(); return NoContent(); } private IEnumerable<object> ProjectTasks(IEnumerable<TaskItem> tasks, string? include) { var fields = (include ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(f => f.ToLowerInvariant()).ToHashSet(); bool all = !fields.Any(); foreach (var t in tasks) { var dict = new Dictionary<string, object?>(); if (all || fields.Contains("id")) dict["id"] = t.Id; if (all || fields.Contains("title")) dict["title"] = t.Title; if (all || fields.Contains("description")) dict["description"] = t.Description; if (all || fields.Contains("priority")) dict["priority"] = t.Priority.ToString(); if (all || fields.Contains("iscompleted")) dict["isCompleted"] = t.IsCompleted; if (all || fields.Contains("userid")) dict["userId"] = t.UserId; yield return dict; } } } }