generated from admin/template
lab-03
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
@@ -1,8 +1,14 @@
|
||||
|
||||
using PokedexApi.Endpoints;
|
||||
using PokedexApi.Storage;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Подключаем OpenAPI
|
||||
builder.Services.AddOpenApi();
|
||||
|
||||
// Регистрируем хранилище как Singleton, чтобы данные не сбрасывались между запросами
|
||||
builder.Services.AddSingleton<PokemonStorage>();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
@@ -10,101 +16,9 @@ if (app.Environment.IsDevelopment())
|
||||
app.MapOpenApi();
|
||||
}
|
||||
|
||||
// Хранилище в памяти
|
||||
var pokemons = new List<Pokemon>
|
||||
{
|
||||
new(1, "Pikachu", "Electric", 12),
|
||||
new(2, "Charmander", "Fire", 8),
|
||||
new(3, "Squirtle", "Water", 10)
|
||||
};
|
||||
|
||||
// Эндпоинты
|
||||
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();
|
||||
});
|
||||
// Подключаем группы эндпоинтов через extension-методы
|
||||
app.MapPokemonEndpoints();
|
||||
app.MapTypeEndpoints();
|
||||
app.MapHealthEndpoints();
|
||||
|
||||
app.Run();
|
||||
|
||||
// ВСЕ МОДЕЛИ И ВСПОМОГАТЕЛЬНЫЕ МЕТОДЫ — СТРОГО В САМОМ НИЗУ ФАЙЛА:
|
||||
|
||||
static List<string> Validate(PokemonInput input)
|
||||
{
|
||||
var allowedTypes = new[] { "Fire", "Water", "Grass", "Electric", "Psychic", "Normal", "Flying", "Poison" };
|
||||
var errors = new List<string>();
|
||||
|
||||
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);
|
||||
@@ -0,0 +1,138 @@
|
||||
using PokedexApi.Models;
|
||||
|
||||
namespace PokedexApi.Storage;
|
||||
|
||||
public class PokemonStorage
|
||||
{
|
||||
private List<Pokemon> _pokemons = new List<Pokemon>
|
||||
{
|
||||
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<Pokemon> GetAll()
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
return new List<Pokemon>(_pokemons);
|
||||
}
|
||||
}
|
||||
|
||||
public Pokemon? GetById(int id)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
foreach (var p in _pokemons)
|
||||
{
|
||||
if (p.Id == id) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public List<Pokemon> Filter(string? type, int? minLevel)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var result = new List<Pokemon>();
|
||||
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<Pokemon> SearchByName(string query)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
var result = new List<Pokemon>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string> Validate(PokemonInput input)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
|
||||
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<string> ValidateLevel(int level)
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (level < 1 || level > 100)
|
||||
{
|
||||
errors.Add("Level должен быть в диапазоне 1..100");
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user