generated from admin/template
api
This commit is contained in:
@@ -11,6 +11,56 @@ var pokemons = new List<Pokemon>
|
||||
new(3, "Squirtle", "Water", 10)
|
||||
};
|
||||
|
||||
app.MapPost("/pokemons", (PokemonInput input) =>
|
||||
{
|
||||
var errors = Validate(input);
|
||||
if (errors.Count > 0)
|
||||
{
|
||||
return Results.BadRequest(errors);
|
||||
}
|
||||
|
||||
var newId = pokemons.Max(p => p.Id) + 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 == 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 == null)
|
||||
{
|
||||
return Results.NotFound();
|
||||
}
|
||||
|
||||
pokemons.Remove(existing);
|
||||
|
||||
return Results.NoContent();
|
||||
|
||||
});
|
||||
|
||||
app.MapGet("/pokemons/{id}", (int id) =>
|
||||
{
|
||||
var pokemon = pokemons.FirstOrDefault(p => p.Id == id);
|
||||
@@ -35,6 +85,28 @@ app.MapGet("/pokemons", () => Results.Ok(pokemons));
|
||||
|
||||
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.IsNullOrEmpty(input.Name) || input.Name.Length < 3)
|
||||
{
|
||||
errors.Add("Name должен быть не короче 2 символов");
|
||||
}
|
||||
|
||||
if (input.Type == null || !allowedTypes.Contains(input.Type))
|
||||
{
|
||||
errors.Add($"Type '{input.Type}' не поддерживается");
|
||||
}
|
||||
if (input.Level < 1 || input.Level > 100)
|
||||
{
|
||||
errors.Add("Level должен быть в диапазоне 1..100");
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
public record Pokemon(
|
||||
int Id,
|
||||
string Name,
|
||||
@@ -45,6 +117,6 @@ public record Pokemon(
|
||||
public record PokemonInput(
|
||||
string Name,
|
||||
string Type,
|
||||
int Level
|
||||
int Level,
|
||||
int Count
|
||||
);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user