Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Воинов Андрей, Букирев Владислав, Ховрычев Андрей <- ФТ-303; Александров Никита <- ФТ301 #40

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions Tests/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ public static void Main()
var testsToRun = new string[]
{
typeof(Task1_GetUserByIdTests).FullName,
//typeof(Task2_CreateUserTests).FullName,
//typeof(Task3_UpdateUserTests).FullName,
//typeof(Task4_PartiallyUpdateUserTests).FullName,
//typeof(Task5_DeleteUserTests).FullName,
//typeof(Task6_HeadUserByIdTests).FullName,
//typeof(Task7_GetUsersTests).FullName,
//typeof(Task8_GetUsersOptionsTests).FullName,
typeof(Task2_CreateUserTests).FullName,
typeof(Task3_UpdateUserTests).FullName,
typeof(Task4_PartiallyUpdateUserTests).FullName,
typeof(Task5_DeleteUserTests).FullName,
typeof(Task6_HeadUserByIdTests).FullName,
typeof(Task7_GetUsersTests).FullName,
typeof(Task8_GetUsersOptionsTests).FullName,
};
new AutoRun().Execute(new[]
{
Expand Down
2 changes: 1 addition & 1 deletion Tests/Task5_DeleteUserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public async Task Test4_Code404_WhenAlreadyCreatedAndDeleted()
lastName = "Condenado"
});

DeleteUser(createdUserId);
await DeleteUser(createdUserId);

var request = new HttpRequestMessage();
request.Method = HttpMethod.Delete;
Expand Down
4 changes: 2 additions & 2 deletions Tests/UsersApiTestsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ protected async Task<string> CreateUser(object user)
return createdUserId;
}

protected void DeleteUser(string userId)
protected async Task DeleteUser(string userId)
{
var request = new HttpRequestMessage();
request.Method = HttpMethod.Delete;
request.RequestUri = BuildUsersByIdUri(userId);
request.Headers.Add("Accept", "*/*");
var response = HttpClient.Send(request);
var response = await HttpClient.SendAsync(request);

response.StatusCode.Should().Be(HttpStatusCode.NoContent);
response.ShouldNotHaveHeader("Content-Type");
Expand Down
213 changes: 206 additions & 7 deletions WebApi.MinimalApi/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,226 @@
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Swashbuckle.AspNetCore.Annotations;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;
using WebApi.MinimalApi.Samples;

namespace WebApi.MinimalApi.Controllers;

[Route("api/[controller]")]
[ApiController]
public class UsersController : Controller
[SwaggerTag("Операции с пользователями")]
public class UsersController : Controller, ISwaggerDescriptionsForUsersController
{
// Чтобы ASP.NET положил что-то в userRepository требуется конфигурация
public UsersController(IUserRepository userRepository)
private IUserRepository Repository;
private IMapper Mapper;
private readonly LinkGenerator linkGenerator;
public UsersController(IUserRepository userRepository, IMapper mapper, LinkGenerator linkGenerator)
{
Repository = userRepository;
Mapper = mapper;
this.linkGenerator = linkGenerator;
}

[HttpGet("{userId}")]
/// <summary>
/// Получить пользователя
/// </summary>
/// <param name="userId">Идентификатор пользователя</param>
[HttpGet("{userId}", Name = nameof(GetUserById))]
[HttpHead("{userId}")]
[Produces("application/json", "application/xml")]
[SwaggerResponse(200, "OK", typeof(UserDto))]
[SwaggerResponse(404, "Пользователь не найден")]
public ActionResult<UserDto> GetUserById([FromRoute] Guid userId)
{
throw new NotImplementedException();
var user = Repository.FindById(userId);
if (user is null)
return NotFound();

var result = Mapper.Map<UserDto>(user);

if (HttpContext.Request.Method != "HEAD")
return Ok(result);

Response.ContentType = "application/json; charset=utf-8";
return Ok();

}

/// <summary>
/// Создать пользователя
/// </summary>
/// <remarks>
/// Пример запроса:
///
/// POST /api/users
/// {
/// "login": "johndoe375",
/// "firstName": "John",
/// "lastName": "Doe"
/// }
///
/// </remarks>
/// <param name="user">Данные для создания пользователя</param>
[HttpPost]
public IActionResult CreateUser([FromBody] object user)
[Consumes("application/json")]
[Produces("application/json", "application/xml")]
[SwaggerResponse(201, "Пользователь создан")]
[SwaggerResponse(400, "Некорректные входные данные")]
[SwaggerResponse(422, "Ошибка при проверке")]
public IActionResult CreateUser([FromBody] AddUserDto user)
{
var createdUserEntity = Mapper.Map<UserEntity>(user);
if (createdUserEntity is null)
return BadRequest();
if(createdUserEntity.Login?.All(char.IsLetterOrDigit) == false)
ModelState.AddModelError(nameof(createdUserEntity.Login).ToLower(), "Login must be letters or digits");
if (!ModelState.IsValid)
return UnprocessableEntity(ModelState);
var createdUser = Repository.Insert(createdUserEntity);
return CreatedAtRoute(
nameof(GetUserById),
new { userId = createdUser.Id },
createdUser.Id);
}

/// <summary>
/// Обновить пользователя
/// </summary>
/// <param name="userId">Идентификатор пользователя</param>
/// <param name="user">Обновленные данные пользователя</param>
[HttpPut("{userId}")]
[Consumes("application/json")]
[Produces("application/json", "application/xml")]
[SwaggerResponse(201, "Пользователь создан")]
[SwaggerResponse(204, "Пользователь обновлен")]
[SwaggerResponse(400, "Некорректные входные данные")]
[SwaggerResponse(422, "Ошибка при проверке")]
public IActionResult UpdateUser(Guid userId, [FromBody] UpdateUserDto user)
{
if (user == null || userId == Guid.Empty)
return BadRequest();
if (!ModelState.IsValid)
return UnprocessableEntity(ModelState);

var userEntity = Mapper.Map(user, new UserEntity(userId));

Repository.UpdateOrInsert(userEntity, out var isInsert);

if (isInsert)
return CreatedAtRoute(
nameof(GetUserById),
new {userId = userId},
userId);
return NoContent();
}

/// <summary>
/// Частично обновить пользователя
/// </summary>
/// <param name="userId">Идентификатор пользователя</param>
/// <param name="patchDoc">JSON Patch для пользователя</param>
[HttpPatch("{userId}")]
[Consumes("application/json-patch+json")]
[Produces("application/json", "application/xml")]
[SwaggerResponse(204, "Пользователь обновлен")]
[SwaggerResponse(400, "Некорректные входные данные")]
[SwaggerResponse(404, "Пользователь не найден")]
[SwaggerResponse(422, "Ошибка при проверке")]
public IActionResult PartiallyUpdateUser(Guid userId, [FromBody] JsonPatchDocument<UpdateUserDto> patchDoc)
{
if (patchDoc == null)
return BadRequest();

var user = Repository.FindById(userId);
if (user == null || userId == Guid.Empty)
return NotFound();

var updateUserDto = Mapper.Map(user, new UpdateUserDto());

patchDoc.ApplyTo(updateUserDto, ModelState);

TryValidateModel(updateUserDto);

if (!ModelState.IsValid)
return UnprocessableEntity(ModelState);

Mapper.Map(updateUserDto, user);

Repository.Update(user);

return NoContent();
}

/// <summary>
/// Удалить пользователя
/// </summary>
/// <param name="userId">Идентификатор пользователя</param>
[HttpDelete("{userId}")]
[Produces("application/json", "application/xml")]
[SwaggerResponse(204, "Пользователь удален")]
[SwaggerResponse(404, "Пользователь не найден")]
public IActionResult DeleteUser(Guid userId)
{
var user = Repository.FindById(userId);
if (user == null)
{
return NotFound();
}

Repository.Delete(userId);

return NoContent();
}

/// <summary>
/// Получить пользователей
/// </summary>
/// <param name="pageNumber">Номер страницы, по умолчанию 1</param>
/// <param name="pageSize">Размер страницы, по умолчанию 20</param>
/// <response code="200">OK</response>
[HttpGet(Name = nameof(GetUsers))]
[Produces("application/json", "application/xml")]
[ProducesResponseType(typeof(IEnumerable<UserDto>), 200)]
public IActionResult GetUsers(int pageNumber = 1, int pageSize = 10)
{
if (pageNumber < 1)
pageNumber = 1;
if (pageSize < 1)
pageSize = 1;
if (pageSize > 20)
pageSize = 20;

var pageList = Repository.GetPage(pageNumber, pageSize);
var users = Mapper.Map<IEnumerable<UserDto>>(pageList);

var paginationHeader = new
{
previousPageLink = pageList.HasPrevious ? linkGenerator.GetUriByRouteValues(HttpContext, nameof(GetUsers), new { pageNumber = pageNumber - 1, pageSize }) : null,
nextPageLink = pageList.HasNext ? linkGenerator.GetUriByRouteValues(HttpContext, nameof(GetUsers), new { pageNumber = pageNumber + 1, pageSize }) : null,
totalCount = pageList.TotalCount,
pageSize = pageList.PageSize,
currentPage = pageList.CurrentPage,
totalPages = pageList.TotalPages
};

Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(paginationHeader));

return Ok(users);
}

/// <summary>
/// Опции по запросам о пользователях
/// </summary>
[HttpOptions]
[SwaggerResponse(200, "OK")]
public IActionResult GetUsersOptions()
{
throw new NotImplementedException();
Response.Headers.Add("Allow", "POST, GET, OPTIONS");

return Ok();
}
}
14 changes: 14 additions & 0 deletions WebApi.MinimalApi/Models/AddUserDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace WebApi.MinimalApi.Models;

public class AddUserDto
{
[Required]
public string Login { get; set; }
[DefaultValue("John")]
public string FirstName { get; set; }
[DefaultValue("Doe")]
public string LastName { get; set; }
}
15 changes: 15 additions & 0 deletions WebApi.MinimalApi/Models/UpdateUserDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace WebApi.MinimalApi.Models;

public class UpdateUserDto
{
[Required]
[RegularExpression("^[0-9\\p{L}]*$", ErrorMessage = "Login should contain only letters or digits")]
public string Login { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
37 changes: 37 additions & 0 deletions WebApi.MinimalApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,50 @@
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;
using WebApi.MinimalApi.Samples;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:5000");
builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options => {
options.SuppressModelStateInvalidFilter = true;
options.SuppressMapClientErrors = true;
})
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Populate;
});

builder.Services.AddSingleton<IUserRepository, InMemoryUserRepository>();
builder.Services.AddControllers(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
options.ReturnHttpNotAcceptable = true;
options.RespectBrowserAcceptHeader = true;
})
.ConfigureApiBehaviorOptions(options =>
{
options.SuppressModelStateInvalidFilter = true;
options.SuppressMapClientErrors = true;
});
builder.Services.AddAutoMapper(cfg =>
{
cfg.CreateMap<UserEntity, UserDto>()
.ForMember(dest => dest.FullName, opt => opt.MapFrom(src => $"{src.LastName} {src.FirstName}"));
cfg.CreateMap<AddUserDto, UserEntity>();
cfg.CreateMap<UpdateUserDto, UserEntity>();
cfg.CreateMap<UserEntity, UpdateUserDto>();

}, new System.Reflection.Assembly[0]);

builder.Services.AddSwaggerGeneration();

var app = builder.Build();

app.MapControllers();

app.UseSwaggerWithUI();
app.Run();
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public interface ISwaggerDescriptionsForUsersController
[SwaggerResponse(201, "Пользователь создан")]
[SwaggerResponse(400, "Некорректные входные данные")]
[SwaggerResponse(422, "Ошибка при проверке")]
IActionResult CreateUser([FromBody] object user);
IActionResult CreateUser([FromBody] AddUserDto user);

/// <summary>
/// Удалить пользователя
Expand All @@ -63,7 +63,7 @@ public interface ISwaggerDescriptionsForUsersController
[SwaggerResponse(204, "Пользователь обновлен")]
[SwaggerResponse(400, "Некорректные входные данные")]
[SwaggerResponse(422, "Ошибка при проверке")]
IActionResult UpdateUser([FromRoute] Guid userId, [FromBody] object user);
IActionResult UpdateUser([FromRoute] Guid userId, [FromBody] UpdateUserDto user);

/// <summary>
/// Частично обновить пользователя
Expand All @@ -78,7 +78,7 @@ public interface ISwaggerDescriptionsForUsersController
[SwaggerResponse(404, "Пользователь не найден")]
[SwaggerResponse(422, "Ошибка при проверке")]
IActionResult PartiallyUpdateUser([FromRoute] Guid userId,
[FromBody] JsonPatchDocument<object> patchDoc);
[FromBody] JsonPatchDocument<UpdateUserDto> patchDoc);

/// <summary>
/// Получить пользователей
Expand Down
Loading