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

Бояков Михаил ФТ-401 #36

Open
wants to merge 4 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
2 changes: 1 addition & 1 deletion Tests/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ namespace Tests
{
public static class Configuration
{
public static string BaseUrl => "http://localhost:5000";
public static string BaseUrl => "http://localhost:5001";
}
}
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
147 changes: 141 additions & 6 deletions WebApi.MinimalApi/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,162 @@
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
using AutoMapper;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;
using WebApi.MinimalApi.Models.Requests;

namespace WebApi.MinimalApi.Controllers;

[Route("api/[controller]")]
[ApiController]
[Route("api/[controller]")]
[Produces("application/json", "application/xml")]
public class UsersController : Controller
{
private readonly IUserRepository userRepository;
private readonly IMapper mapper;
private readonly LinkGenerator linkGenerator;

// Чтобы ASP.NET положил что-то в userRepository требуется конфигурация
public UsersController(IUserRepository userRepository)
public UsersController(IUserRepository userRepository, IMapper mapper, LinkGenerator linkGenerator)
{
this.userRepository = userRepository;
this.mapper = mapper;
this.linkGenerator = linkGenerator;
}

/// <summary>
/// Returns user by its id
/// </summary>
[HttpHead("{userId}")]
[HttpGet("{userId}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<UserDto> GetUserById([FromRoute] Guid userId)
{
throw new NotImplementedException();
if (HttpMethods.IsHead(Request.Method))
Response.Body = Stream.Null;
var user = userRepository.FindById(userId);
return user is not null ? Ok(mapper.Map<UserDto>(user)) : NotFound();
}

/// <summary>
/// Creates user and returns its id
/// </summary>
[HttpPost]
public IActionResult CreateUser([FromBody] object user)
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
public IActionResult CreateUser([FromBody] CreateUserRequest request)
{
if (request is null)
return BadRequest();
if (!request.Login?.All(char.IsAsciiLetterOrDigit) is true)
ModelState.AddModelError("Login", "Login should contain only digits and letters");
if (!ModelState.IsValid)
return UnprocessableEntity(ModelState);
var entity = mapper.Map<UserEntity>(request);
var result = userRepository.Insert(entity);
return CreatedAtAction(nameof(GetUserById), new { userId = result.Id }, result.Id);
}

/// <summary>
/// Changes user by id or creates if doesn't exist
/// </summary>
[HttpPut("{userId}")]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
public IActionResult UpsertUser([FromRoute] Guid userId, [FromBody] UpdateUserRequest request)
{
if (request is null || userId == Guid.Empty)
return BadRequest();
if (!ModelState.IsValid)
return UnprocessableEntity(ModelState);
var entity = mapper.Map<UserEntity>(request);
entity.Id = userId;
userRepository.UpdateOrInsert(entity, out var inserted);
return inserted
? CreatedAtAction(nameof(GetUserById), new { userId }, userId)
: NoContent();
}

/// <summary>
/// Updates user data
/// </summary>
[HttpPatch("{userId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
public IActionResult PartiallyUpdateUser([FromRoute] Guid userId, [FromBody] JsonPatchDocument<UpdateUserRequest> patchDoc)
{
if (patchDoc is null)
return BadRequest();
var user = userRepository.FindById(userId);
if (user is null)
return NotFound();
var update = mapper.Map<UpdateUserRequest>(user);
patchDoc.ApplyTo(update, ModelState);
TryValidateModel(update);
if (!ModelState.IsValid)
return UnprocessableEntity(ModelState);
var entity = mapper.Map<UserEntity>(update);
entity.Id = userId;
userRepository.Update(entity);
return NoContent();
}

/// <summary>
/// Deletes user
/// </summary>
[HttpDelete("{userId}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult DeleteUser([FromRoute] Guid userId)
{
if (userRepository.FindById(userId) is null)
return NotFound();
userRepository.Delete(userId);
return NoContent();
}

/// <summary>
/// Get all users
/// </summary>
[HttpGet(Name = nameof(GetUsers))]
[ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<IEnumerable<UserDto>> GetUsers(
[FromQuery] int pageNumber = 1,
[FromQuery] int pageSize = 10)
{
pageSize = Math.Clamp(pageSize, 1, 20);
pageNumber = Math.Max(pageNumber, 1);
var pageList = userRepository.GetPage(pageNumber, pageSize);
var paginationInfo = 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,
pageList.TotalCount,
pageList.PageSize,
pageList.CurrentPage,
pageList.TotalPages,
};
Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(paginationInfo));
return Ok(mapper.Map<IEnumerable<UserDto>>(pageList));
}

[HttpOptions]
[ProducesResponseType(StatusCodes.Status200OK)]
public IActionResult Options()
{
throw new NotImplementedException();
var allowedMethods = new[] { HttpMethods.Get, HttpMethods.Options, HttpMethods.Post };
Response.Headers.Add("Allow", string.Join(", ", allowedMethods));
return Ok();
}
}
2 changes: 1 addition & 1 deletion WebApi.MinimalApi/Domain/UserEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public Guid Id
{
get;
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Local For MongoDB
private set;
internal set;
}

/// <summary>
Expand Down
14 changes: 14 additions & 0 deletions WebApi.MinimalApi/Models/Requests/CreateUserRequest.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.Requests;

public class CreateUserRequest
{
[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/Requests/UpdateUserRequest.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.Requests;

public class UpdateUserRequest
{
[Required]
[RegularExpression("[a-zA-Z0-9]+", 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; }
}
50 changes: 47 additions & 3 deletions WebApi.MinimalApi/Program.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,57 @@
using System.Reflection;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using WebApi.MinimalApi.Domain;
using WebApi.MinimalApi.Models;
using WebApi.MinimalApi.Models.Requests;

var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://localhost:5000");
builder.Services.AddControllers()
.ConfigureApiBehaviorOptions(options => {
builder.WebHost.UseUrls("http://localhost:5001");
builder.Services.AddControllers(options =>
{
options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
options.ReturnHttpNotAcceptable = true;
options.RespectBrowserAcceptHeader = true;
})
.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.AddAutoMapper(cfg =>
{
cfg.CreateMap<UserEntity, UpdateUserRequest>();
cfg.CreateMap<UserEntity, UserDto>()
.ForMember(dto => dto.FullName,
opt => opt.MapFrom(user => $"{user.LastName} {user.FirstName}"));
cfg.CreateMap<CreateUserRequest, UserEntity>();
cfg.CreateMap<UpdateUserRequest, UserEntity>();
}, Array.Empty<Assembly>());
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseRouting();
app.MapGet("/test", () => "Test");
app.MapControllers();

app.Run();
2 changes: 1 addition & 1 deletion WebApi.MinimalApi/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"applicationUrl": "http://localhost:5001",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
Expand Down
55 changes: 28 additions & 27 deletions WebApi.MinimalApi/WebApi.MinimalApi.csproj
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>11</LangVersion>
</PropertyGroup>

<ItemGroup>
<InternalsVisibleTo Include="Tests"/>
</ItemGroup>
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<LangVersion>11</LangVersion>
</PropertyGroup>

<ItemGroup>
<None Include="Samples\GameApi.postman_collection.json" />
<None Include="Samples\UsersApi.postman_collection.json" />
<None Include="Samples\ValuesApi.postman_collection.json" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Tests"/>
</ItemGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1" />
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="8.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.2" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="Swashbuckle" Version="5.6.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.5.0" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0" />
</ItemGroup>
<ItemGroup>
<None Include="Samples\GameApi.postman_collection.json"/>
<None Include="Samples\UsersApi.postman_collection.json"/>
<None Include="Samples\ValuesApi.postman_collection.json"/>
</ItemGroup>

<ItemGroup>
<PackageReference Include="AutoMapper" Version="13.0.1"/>
<PackageReference Include="Microsoft.AspNetCore.JsonPatch" Version="8.0.2"/>
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="8.0.2"/>
<PackageReference Include="NUnit" Version="3.13.3"/>
<PackageReference Include="Swashbuckle" Version="5.6.0"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
<PackageReference Include="Swashbuckle.AspNetCore.Annotations" Version="6.5.0"/>
<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="6.5.0"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="6.5.0"/>
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="6.5.0"/>
</ItemGroup>

</Project>