From c8c754c9a410202c38a8ee5ff50fa12dc69ceff4 Mon Sep 17 00:00:00 2001 From: zxc Date: Fri, 16 Oct 2026 17:12:18 +0300 Subject: [PATCH] lab-03 --- .../PokedexApi/Endpoints/HealthEndpoints.cs | 13 ++ .../PokedexApi/Endpoints/PokemonEndpoints.cs | 92 ++++++++++++ .../PokedexApi/Endpoints/TypeEndpoints.cs | 36 +++++ .../PokedexApi/PokedexApi/Models/Pokemon.cs | 5 + .../part2/PokedexApi/PokedexApi/Program.cs | 110 ++------------ .../PokedexApi/Storage/PokemonStorage.cs | 138 ++++++++++++++++++ .../PokedexApi/Validation/PokemonValidator.cs | 49 +++++++ 7 files changed, 345 insertions(+), 98 deletions(-) create mode 100644 works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/HealthEndpoints.cs create mode 100644 works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/PokemonEndpoints.cs create mode 100644 works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/TypeEndpoints.cs create mode 100644 works/lab-02/part2/PokedexApi/PokedexApi/Models/Pokemon.cs create mode 100644 works/lab-02/part2/PokedexApi/PokedexApi/Storage/PokemonStorage.cs create mode 100644 works/lab-02/part2/PokedexApi/PokedexApi/Validation/PokemonValidator.cs diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/HealthEndpoints.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/HealthEndpoints.cs new file mode 100644 index 0000000..5385036 --- /dev/null +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/HealthEndpoints.cs @@ -0,0 +1,13 @@ +namespace PokedexApi.Endpoints; + +public static class HealthEndpoints +{ + public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/health").WithTags("Health"); + + group.MapGet("/", () => Results.Ok(new { status = "healthy", timestamp = DateTime.UtcNow })); + + return app; + } +} \ No newline at end of file diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/PokemonEndpoints.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/PokemonEndpoints.cs new file mode 100644 index 0000000..6a2616a --- /dev/null +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/PokemonEndpoints.cs @@ -0,0 +1,92 @@ +using PokedexApi.Models; +using PokedexApi.Storage; +using PokedexApi.Validation; + +namespace PokedexApi.Endpoints; + +public static class PokemonEndpoints +{ + public static IEndpointRouteBuilder MapPokemonEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/pokemons").WithTags("Pokemons"); + + group.MapGet("/", (string? type, int? minLevel, PokemonStorage storage) => + { + return Results.Ok(storage.Filter(type, minLevel)); + }); + + group.MapGet("/{id:int}", (int id, PokemonStorage storage) => + { + var pokemon = storage.GetById(id); + if (pokemon == null) + { + return Results.NotFound(); + } + return Results.Ok(pokemon); + }); + + group.MapGet("/search", (string? name, PokemonStorage storage) => + { + if (string.IsNullOrWhiteSpace(name)) + { + return Results.BadRequest(new { errors = new string[] { "Параметр name обязателен" } }); + } + return Results.Ok(storage.SearchByName(name!)); + }); + + group.MapPost("/", (PokemonInput input, PokemonStorage storage) => + { + var errors = PokemonValidator.Validate(input); + if (errors.Count > 0) + { + return Results.BadRequest(new { errors = errors }); + } + + var pokemon = storage.Add(input); + return Results.Created("/pokemons/" + pokemon.Id, pokemon); + }); + + group.MapPut("/{id:int}", (int id, PokemonInput input, PokemonStorage storage) => + { + var errors = PokemonValidator.Validate(input); + if (errors.Count > 0) + { + return Results.BadRequest(new { errors = errors }); + } + + var updated = storage.Update(id, input); + if (updated == null) + { + return Results.NotFound(); + } + return Results.Ok(updated); + }); + + group.MapPatch("/{id:int}/level", (int id, LevelUpdate update, PokemonStorage storage) => + { + var errors = PokemonValidator.ValidateLevel(update.Level); + if (errors.Count > 0) + { + return Results.BadRequest(new { errors = errors }); + } + + var updated = storage.UpdateLevel(id, update.Level); + if (updated == null) + { + return Results.NotFound(); + } + return Results.Ok(updated); + }); + + group.MapDelete("/{id:int}", (int id, PokemonStorage storage) => + { + if (storage.Delete(id)) + { + return Results.NoContent(); + } + return Results.NotFound(); + }); + + return app; + } +} \ No newline at end of file diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/TypeEndpoints.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/TypeEndpoints.cs new file mode 100644 index 0000000..7a8a874 --- /dev/null +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Endpoints/TypeEndpoints.cs @@ -0,0 +1,36 @@ +using PokedexApi.Storage; +using PokedexApi.Validation; + +namespace PokedexApi.Endpoints; + +public static class TypeEndpoints +{ + public static IEndpointRouteBuilder MapTypeEndpoints(this IEndpointRouteBuilder app) + { + var group = app.MapGroup("/types").WithTags("Types"); + + group.MapGet("/", () => Results.Ok(PokemonValidator.AllowedTypes)); + + group.MapGet("/{type}", (string type, PokemonStorage storage) => + { + bool typeOk = false; + foreach (var t in PokemonValidator.AllowedTypes) + { + if (t.Equals(type, StringComparison.OrdinalIgnoreCase)) + { + typeOk = true; + break; + } + } + + if (!typeOk) + { + return Results.BadRequest(new { errors = new string[] { "Type '" + type + "' не поддерживается" } }); + } + + return Results.Ok(storage.Filter(type, null)); + }); + + return app; + } +} \ No newline at end of file diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Models/Pokemon.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Models/Pokemon.cs new file mode 100644 index 0000000..f3fe2c9 --- /dev/null +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Models/Pokemon.cs @@ -0,0 +1,5 @@ +namespace PokedexApi.Models; + +public record Pokemon(int Id, string Name, string Type, int Level); +public record PokemonInput(string Name, string Type, int Level); +public record LevelUpdate(int Level); \ No newline at end of file diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Program.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Program.cs index e39f9ed..be03298 100644 --- a/works/lab-02/part2/PokedexApi/PokedexApi/Program.cs +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Program.cs @@ -1,8 +1,14 @@ + +using PokedexApi.Endpoints; +using PokedexApi.Storage; + var builder = WebApplication.CreateBuilder(args); -// Подключаем OpenAPI builder.Services.AddOpenApi(); +// Регистрируем хранилище как Singleton, чтобы данные не сбрасывались между запросами +builder.Services.AddSingleton(); + var app = builder.Build(); if (app.Environment.IsDevelopment()) @@ -10,101 +16,9 @@ if (app.Environment.IsDevelopment()) app.MapOpenApi(); } -// Хранилище в памяти -var pokemons = new List -{ - new(1, "Pikachu", "Electric", 12), - new(2, "Charmander", "Fire", 8), - new(3, "Squirtle", "Water", 10) -}; +// Подключаем группы эндпоинтов через extension-методы +app.MapPokemonEndpoints(); +app.MapTypeEndpoints(); +app.MapHealthEndpoints(); -// Эндпоинты -app.MapGet("/hello", () => "Привет, мир API!"); - -app.MapGet("/pokemons", () => Results.Ok(pokemons)); - -app.MapGet("/pokemons/{id}", (int id) => -{ - var pokemon = pokemons.FirstOrDefault(p => p.Id == id); - return pokemon is null - ? Results.NotFound() - : Results.Ok(pokemon); -}); - -app.MapPost("/pokemons", (PokemonInput input) => -{ - var errors = Validate(input); - if (errors.Count > 0) - { - return Results.BadRequest(new { errors }); - } - - var newId = pokemons.Count > 0 ? pokemons.Max(p => p.Id) + 1 : 1; - var pokemon = new Pokemon(newId, input.Name, input.Type, input.Level); - pokemons.Add(pokemon); - - return Results.Created($"/pokemons/{newId}", pokemon); -}); - -app.MapPut("/pokemons/{id}", (int id, PokemonInput input) => -{ - var existing = pokemons.FirstOrDefault(p => p.Id == id); - if (existing is null) - { - return Results.NotFound(); - } - - var errors = Validate(input); - if (errors.Count > 0) - { - return Results.BadRequest(new { errors }); - } - - var updated = new Pokemon(id, input.Name, input.Type, input.Level); - pokemons[pokemons.IndexOf(existing)] = updated; - - return Results.Ok(updated); -}); - -app.MapDelete("/pokemons/{id}", (int id) => -{ - var existing = pokemons.FirstOrDefault(p => p.Id == id); - if (existing is null) - { - return Results.NotFound(); - } - - pokemons.Remove(existing); - return Results.NoContent(); -}); - -app.Run(); - -// ВСЕ МОДЕЛИ И ВСПОМОГАТЕЛЬНЫЕ МЕТОДЫ — СТРОГО В САМОМ НИЗУ ФАЙЛА: - -static List Validate(PokemonInput input) -{ - var allowedTypes = new[] { "Fire", "Water", "Grass", "Electric", "Psychic", "Normal", "Flying", "Poison" }; - var errors = new List(); - - if (string.IsNullOrWhiteSpace(input.Name) || input.Name.Length < 2) - { - errors.Add("Name должен быть не короче 2 символов"); - } - - if (!allowedTypes.Contains(input.Type)) - { - errors.Add($"Type '{input.Type}' не поддерживается"); - } - - if (input.Level is < 1 or > 100) - { - errors.Add("Level должен быть в диапазоне 1..100"); - } - - return errors; -} - -// Объявление записей (records) тоже в самом низу -public record Pokemon(int Id, string Name, string Type, int Level); -public record PokemonInput(string Name, string Type, int Level); \ No newline at end of file +app.Run(); \ No newline at end of file diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Storage/PokemonStorage.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Storage/PokemonStorage.cs new file mode 100644 index 0000000..b3a347f --- /dev/null +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Storage/PokemonStorage.cs @@ -0,0 +1,138 @@ +using PokedexApi.Models; + +namespace PokedexApi.Storage; + +public class PokemonStorage +{ + private List _pokemons = new List + { + new Pokemon(1, "Pikachu", "Electric", 12), + new Pokemon(2, "Charmander", "Fire", 8), + new Pokemon(3, "Squirtle", "Water", 10) + }; + + private readonly object _lock = new object(); + + public List GetAll() + { + lock (_lock) + { + return new List(_pokemons); + } + } + + public Pokemon? GetById(int id) + { + lock (_lock) + { + foreach (var p in _pokemons) + { + if (p.Id == id) return p; + } + return null; + } + } + + public List Filter(string? type, int? minLevel) + { + lock (_lock) + { + var result = new List(); + foreach (var p in _pokemons) + { + if (type != null && p.Type != type) continue; + if (minLevel != null && p.Level < minLevel) continue; + result.Add(p); + } + return result; + } + } + + public List SearchByName(string query) + { + lock (_lock) + { + var result = new List(); + foreach (var p in _pokemons) + { + if (p.Name.ToLower().Contains(query.ToLower())) + { + result.Add(p); + } + } + return result; + } + } + + public Pokemon Add(PokemonInput input) + { + lock (_lock) + { + int newId = 1; + foreach (var p in _pokemons) + { + if (p.Id >= newId) newId = p.Id + 1; + } + var pokemon = new Pokemon(newId, input.Name, input.Type, input.Level); + _pokemons.Add(pokemon); + return pokemon; + } + } + + public Pokemon? Update(int id, PokemonInput input) + { + lock (_lock) + { + for (int i = 0; i < _pokemons.Count; i++) + { + if (_pokemons[i].Id == id) + { + var updated = new Pokemon(id, input.Name, input.Type, input.Level); + _pokemons[i] = updated; + return updated; + } + } + return null; + } + } + + public Pokemon? UpdateLevel(int id, int level) + { + lock (_lock) + { + for (int i = 0; i < _pokemons.Count; i++) + { + var existing = _pokemons[i]; + if (existing.Id == id) + { + var updated = new Pokemon(existing.Id, existing.Name, existing.Type, level); + _pokemons[i] = updated; + return updated; + } + } + return null; + } + } + + public bool Delete(int id) + { + lock (_lock) + { + Pokemon? found = null; + foreach (var p in _pokemons) + { + if (p.Id == id) + { + found = p; + break; + } + } + if (found != null) + { + _pokemons.Remove(found); + return true; + } + return false; + } + } +} \ No newline at end of file diff --git a/works/lab-02/part2/PokedexApi/PokedexApi/Validation/PokemonValidator.cs b/works/lab-02/part2/PokedexApi/PokedexApi/Validation/PokemonValidator.cs new file mode 100644 index 0000000..c016b51 --- /dev/null +++ b/works/lab-02/part2/PokedexApi/PokedexApi/Validation/PokemonValidator.cs @@ -0,0 +1,49 @@ +using PokedexApi.Models; + +namespace PokedexApi.Validation; + +public static class PokemonValidator +{ + public static readonly string[] AllowedTypes = new string[] + { + "Fire", "Water", "Grass", "Electric", + "Psychic", "Normal", "Flying", "Poison" + }; + + public static List Validate(PokemonInput input) + { + var errors = new List(); + + if (string.IsNullOrWhiteSpace(input.Name) || input.Name.Length < 2) + { + errors.Add("Name должен быть не короче 2 символов"); + } + + bool typeOk = false; + foreach (var t in AllowedTypes) + { + if (t == input.Type) typeOk = true; + } + if (!typeOk) + { + errors.Add("Type '" + input.Type + "' не поддерживается"); + } + + if (input.Level < 1 || input.Level > 100) + { + errors.Add("Level должен быть в диапазоне 1..100"); + } + + return errors; + } + + public static List ValidateLevel(int level) + { + var errors = new List(); + if (level < 1 || level > 100) + { + errors.Add("Level должен быть в диапазоне 1..100"); + } + return errors; + } +} \ No newline at end of file