Menu
CoddyTech

Ordenación

Parte de la sección API REST del Journey de ASP.NET Core de Coddy. Lección 12 de 20.

Un parámetro sort permite que el cliente elija el orden: GET /api/products?sort=price. Acepta solo los órdenes que admites y responde con 400 para cualquier otro, de modo que se informe de un error tipográfico como sort=prise en lugar de ignorarlo.

var errors = new Dictionary<string, string[]>();
if (sort is not null && sort != "name" && sort != "price")
    errors["sort"] = ["Sort by name or price."];
if (errors.Count > 0) return Results.ValidationProblem(errors);

if (sort == "price") result = result.OrderBy(p => p.Price);

OrderBy devuelve una secuencia nueva y ordenada, y no modifica la lista. products.Sort(...) reordenaría la lista almacenada, así que todas las respuestas posteriores también devolverían los elementos en el nuevo orden. Recopilar los errores en un solo diccionario permite informar de todos ellos a la vez cuando una solicitud contiene varios errores.

challenge icon

Desafío

Fácil

Permite que los clientes ordenen las tareas por título.

  1. Agrega un tercer parámetro a la lambda de GET /api/tasks: string? sort.
  2. Al inicio de la lambda, recopila los errores en un diccionario. Cuando sort no sea null, id ni title, agrega Sort by id or title. bajo sort y responde con Results.ValidationProblem(errors) cuando el diccionario contenga algún error.
  3. Después de los filtros, cuando sort sea title, ordena el resultado por título con OrderBy. Sin sort, o con sort=id, las tareas se mantienen ordenadas por id.

GET /api/tasks?sort=title responde con las tareas 2, 3 y 1: Book, Send, Write.

Pruébalo: pulsa «Ejecutar» y envía GET /api/tasks?sort=title: el orden anterior. Envía GET /api/tasks: vuelven a estar ordenadas por id. Envía GET /api/tasks?sort=size: 400 con "errors": { "sort": ["Sort by id or title."] }. Envía GET /api/tasks?done=false&sort=title: las tareas 3 y 1.

Pruébalo tú mismo

using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app = builder.Build();

app.UseExceptionHandler();
app.UseStatusCodePages();

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};
var nextId = 4;

bool TitleTaken(string title, int exceptId) =>
    tasks.Any(t => t.Id != exceptId && string.Equals(t.Title, title, StringComparison.OrdinalIgnoreCase));

app.MapGet("/api/tasks", (bool? done, string? search) =>
{
    IEnumerable<TaskItem> result = tasks;
    if (done is not null) result = result.Where(t => t.Done == done);
    if (!string.IsNullOrWhiteSpace(search))
        result = result.Where(t => t.Title.Contains(search, StringComparison.OrdinalIgnoreCase));
    return Results.Ok(result);
});

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    if (TitleTaken(input.Title, 0))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    if (TitleTaken(input.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    tasks[index] = new TaskItem(id, input.Title, input.Done);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    if (patch.Title is not null && TitleTaken(patch.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);

Todas las lecciones de API REST