-
Notifications
You must be signed in to change notification settings - Fork 24
Казаков Андрей Лаб. 1 Группа 6513 #15
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
Open
Gironape
wants to merge
11
commits into
itsecd:main
Choose a base branch
from
Gironape:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+732
−133
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
3eb0932
Начало?
Gironape 27f7867
тест
Gironape c36dd20
еще тест
Gironape 68dcf77
Облажался....
Gironape f7c703c
Испарвления
Gironape 58725bb
Delete WeatherForecastController.cs
Gironape 06de5f2
Продолжаю не спать
Gironape 361302a
Я уже близко к разгадке
Gironape e55fc94
Что-то получилось
Gironape adec247
Delete README.md
Gironape 7a0df48
Наворотил исправления
Gironape File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,5 +6,5 @@ | |
| } | ||
| }, | ||
| "AllowedHosts": "*", | ||
| "BaseAddress": "" | ||
| "BaseAddress": "https://localhost:7106/api/employee" | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="9.3.1" /> | ||
| <PackageReference Include="Bogus" Version="35.6.5" /> | ||
| <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Client.Wasm\Client.Wasm.csproj" /> | ||
| <ProjectReference Include="..\CompanyEmployee.Domain\CompanyEmployee.Domain.csproj" /> | ||
| <ProjectReference Include="..\CompanyEmployee.ServiceDefaults\CompanyEmployee.ServiceDefaults.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ProjectExtensions><VisualStudio><UserProperties properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| using CompanyEmployee.Api.Services; | ||
| using CompanyEmployee.Domain.Entity; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace CompanyEmployee.Api.Controllers; | ||
|
|
||
| /// <summary> | ||
| /// Контроллер для работы с сотрудниками. | ||
| /// </summary> | ||
| /// <param name="employeeService">Сервис для получения сотрудников с кэшированием.</param> | ||
| /// <param name="logger">Логгер для записи информации о запросах.</param> | ||
| [ApiController] | ||
| [Route("api/[controller]")] | ||
| public class EmployeeController( | ||
| IEmployeeService employeeService, | ||
| ILogger<EmployeeController> logger) : ControllerBase | ||
| { | ||
| /// <summary> | ||
| /// Получить сотрудника по идентификатору. | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор сотрудника.</param> | ||
| /// <param name="cancellationToken">Токен отмены операции.</param> | ||
| /// <returns>Объект сотрудника.</returns> | ||
| [HttpGet] | ||
| [ProducesResponseType(typeof(Employee), StatusCodes.Status200OK)] | ||
| [ProducesResponseType(StatusCodes.Status400BadRequest)] | ||
| [ProducesResponseType(StatusCodes.Status404NotFound)] | ||
| [ProducesResponseType(StatusCodes.Status500InternalServerError)] | ||
| public async Task<ActionResult<Employee>> GetEmployee(int id, CancellationToken cancellationToken) | ||
| { | ||
| try | ||
| { | ||
| logger.LogInformation("Запрос на получение сотрудника с id: {Id}", id); | ||
|
|
||
| if (id <= 0) | ||
| { | ||
| return BadRequest("ID должен быть положительным числом"); | ||
| } | ||
|
|
||
| var employee = await employeeService.GetEmployeeAsync(id, cancellationToken); | ||
|
|
||
| if (employee == null) | ||
| { | ||
| return NotFound($"Сотрудник с ID {id} не найден"); | ||
| } | ||
|
|
||
| return Ok(employee); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| logger.LogError(ex, "Ошибка при получении сотрудника с id: {Id}", id); | ||
| return StatusCode(500, "Внутренняя ошибка сервера"); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| using CompanyEmployee.Api.Services; | ||
| using CompanyEmployee.ServiceDefaults; | ||
|
|
||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| builder.AddServiceDefaults(); | ||
| builder.AddRedisDistributedCache("redis"); | ||
| builder.Services.AddControllers(); | ||
| builder.Services.AddEndpointsApiExplorer(); | ||
| builder.Services.AddSwaggerGen(); | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddPolicy("wasm", policy => | ||
| { | ||
| policy.AllowAnyOrigin() | ||
| .WithMethods("GET") | ||
| .WithHeaders("Content-Type"); | ||
| }); | ||
| }); | ||
|
|
||
| builder.Services.AddSingleton<IEmployeeGenerator, EmployeeGenerator>(); | ||
| builder.Services.AddSingleton<ICacheService, RedisCacheService>(); | ||
| builder.Services.AddScoped<IEmployeeService, EmployeeService>(); | ||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.UseSwagger(); | ||
| app.UseSwaggerUI(); | ||
| } | ||
|
|
||
| app.MapDefaultEndpoints(); | ||
| app.UseHttpsRedirection(); | ||
| app.UseCors("wasm"); | ||
| app.UseAuthorization(); | ||
| app.MapControllers(); | ||
| app.Run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| { | ||
| "$schema": "http://json.schemastore.org/launchsettings.json", | ||
| "iisSettings": { | ||
| "windowsAuthentication": false, | ||
| "anonymousAuthentication": true, | ||
| "iisExpress": { | ||
| "applicationUrl": "http://localhost:56739", | ||
| "sslPort": 44378 | ||
| } | ||
| }, | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "http://localhost:5121", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "applicationUrl": "https://localhost:7106;http://localhost:5121", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "IIS Express": { | ||
| "commandName": "IISExpress", | ||
| "launchBrowser": true, | ||
| "launchUrl": "swagger", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| using Bogus; | ||
| using Bogus.DataSets; | ||
| using CompanyEmployee.Domain.Entity; | ||
|
|
||
| namespace CompanyEmployee.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Генератор сотрудников. | ||
| /// </summary> | ||
| /// <param name="logger">Логгер.</param> | ||
| public class EmployeeGenerator(ILogger<EmployeeGenerator> logger) : IEmployeeGenerator | ||
| { | ||
| private readonly string[] _professions = { "Developer", "Manager", "Analyst", "Designer", "QA" }; | ||
| private readonly string[] _suffixes = { "Junior", "Middle", "Senior" }; | ||
|
|
||
| /// <inheritdoc /> | ||
| public Employee Generate(int id) | ||
| { | ||
| Randomizer.Seed = new Random(id); | ||
| var faker = new Faker("ru"); | ||
| var employee = new Faker<Employee>("ru") | ||
| .RuleFor(e => e.Id, id) | ||
| .RuleFor(e => e.FullName, f => | ||
| { | ||
| var gender = f.PickRandom<Name.Gender>(); | ||
| var firstName = f.Name.FirstName(gender); | ||
| var lastName = f.Name.LastName(gender); | ||
| var fatherName = f.Name.FirstName(Name.Gender.Male); | ||
| var patronymic = gender == Name.Gender.Male | ||
| ? fatherName.EndsWith("й") || fatherName.EndsWith("ь") | ||
| ? fatherName[..^1] + "евич" | ||
| : fatherName + "ович" | ||
| : fatherName.EndsWith("й") || fatherName.EndsWith("ь") | ||
| ? fatherName[..^1] + "евна" | ||
| : fatherName + "овна"; | ||
|
|
||
| return $"{lastName} {firstName} {patronymic}"; | ||
| }) | ||
| .RuleFor(e => e.Position, f => | ||
| { | ||
| var profession = f.PickRandom(_professions); | ||
| var suffix = f.PickRandom(_suffixes); | ||
| return $"{profession} {suffix}"; | ||
| }) | ||
| .RuleFor(e => e.Department, f => f.Commerce.Department()) | ||
| .RuleFor(e => e.HireDate, f => | ||
| DateOnly.FromDateTime(f.Date.Past(10).ToUniversalTime())) | ||
| .RuleFor(e => e.Salary, f => | ||
| { | ||
| var suffix = f.PickRandom(_suffixes); | ||
| var salary = suffix switch | ||
| { | ||
| "Junior" => f.Random.Decimal(30000, 60000), | ||
| "Middle" => f.Random.Decimal(60000, 100000), | ||
| "Senior" => f.Random.Decimal(100000, 180000), | ||
| _ => f.Random.Decimal(40000, 80000) | ||
| }; | ||
| return Math.Round(salary, 2); | ||
| }) | ||
| .RuleFor(e => e.Email, (f, e) => | ||
| { | ||
| var nameParts = e.FullName.Split(' '); | ||
| return f.Internet.Email(nameParts[1], nameParts[0], "company.ru"); | ||
| }) | ||
| .RuleFor(e => e.Phone, f => f.Phone.PhoneNumber("+7(###)###-##-##")) | ||
| .RuleFor(e => e.IsTerminated, f => f.Random.Bool(0.1f)) | ||
| .RuleFor(e => e.TerminationDate, (f, e) => | ||
| e.IsTerminated | ||
| ? DateOnly.FromDateTime(f.Date.Between( | ||
| e.HireDate.ToDateTime(TimeOnly.MinValue), | ||
| DateTime.Now)) | ||
| : null) | ||
| .Generate(); | ||
|
|
||
| logger.LogInformation("Сгенерирован сотрудник ID {Id}: {FullName}", employee.Id, employee.FullName); | ||
| return employee; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| using CompanyEmployee.Domain.Entity; | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
|
|
||
| namespace CompanyEmployee.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Бизнес-логика работы с сотрудниками. | ||
| /// </summary> | ||
| /// <param name="generator">Генератор сотрудников.</param> | ||
| /// <param name="cache">Сервис кэширования.</param> | ||
| /// <param name="logger">Логгер.</param> | ||
| public class EmployeeService( | ||
| IEmployeeGenerator generator, | ||
| ICacheService cache, | ||
| ILogger<EmployeeService> logger) : IEmployeeService | ||
| { | ||
| private readonly DistributedCacheEntryOptions _cacheOptions = new() | ||
| { | ||
| AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) | ||
| }; | ||
|
|
||
| /// <inheritdoc /> | ||
| public async Task<Employee?> GetEmployeeAsync(int id, CancellationToken cancellationToken = default) | ||
| { | ||
| var cacheKey = $"employee:{id}"; | ||
| var employee = await cache.GetAsync<Employee>(cacheKey, cancellationToken); | ||
| if (employee != null) | ||
| { | ||
| logger.LogInformation("Сотрудник с ID {Id} найден в кэше", id); | ||
| return employee; | ||
| } | ||
|
|
||
| logger.LogInformation("Сотрудник с ID {Id} не найден в кэше, генерация нового", id); | ||
| employee = generator.Generate(id); | ||
|
|
||
| await cache.SetAsync(cacheKey, employee, _cacheOptions, cancellationToken); | ||
|
|
||
| return employee; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| using Microsoft.Extensions.Caching.Distributed; | ||
|
|
||
| namespace CompanyEmployee.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Сервис для работы с распределённым кэшем. | ||
| /// </summary> | ||
| public interface ICacheService | ||
| { | ||
| /// <summary>Получает данные из кэша по ключу.</summary> | ||
| /// <param name="key">Ключ кэша.</param> | ||
| /// <param name="cancellationToken">Токен отмены.</param> | ||
| /// <returns>Данные из кэша или default.</returns> | ||
| public Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default); | ||
|
|
||
| /// <summary>Сохраняет данные в кэш.</summary> | ||
| /// <param name="key">Ключ кэша.</param> | ||
| /// <param name="value">Данные для сохранения.</param> | ||
| /// <param name="options">Опции кэширования.</param> | ||
| /// <param name="cancellationToken">Токен отмены.</param> | ||
| public Task SetAsync<T>(string key, T value, DistributedCacheEntryOptions? options = null, CancellationToken cancellationToken = default); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| using CompanyEmployee.Domain.Entity; | ||
|
|
||
| namespace CompanyEmployee.Api.Services; | ||
|
|
||
| /// <summary> | ||
| /// Генератор данных сотрудников. | ||
| /// </summary> | ||
| public interface IEmployeeGenerator | ||
| { | ||
| /// <summary> | ||
| /// Генерирует сотрудника по идентификатору. | ||
| /// </summary> | ||
| /// <param name="id">Идентификатор.</param> | ||
| /// <returns>Сгенерированный сотрудник.</returns> | ||
| public Employee Generate(int id); | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Нет саммари