Menu
CoddyTech

Mức độ ưu tiên của tác vụ

Thuộc phần REST API trong hành trình ASP.NET Core của Coddy. Bài học 14 trên 20.

Chương này là một dự án: bạn thêm một tính năng xuyên suốt API bằng những gì đã học. Một số công việc cần xử lý gấp, nên mỗi công việc có một mức độ ưu tiên: 1 là cao, 2 là bình thường, 3 là thấp.

record Seat(int Row, [property: Range(1, 40)] int Number = 1);

[Range(1, 40)] từ chối số nằm ngoài khoảng từ 1 đến 40 với thông báo The field Number must be between 1 and 40. Giá trị mặc định trong một bản ghi vị trí (= 1) sẽ được dùng khi nội dung JSON không có trường này. Với thuộc tính có thể nhận giá trị null, Range cho phép null, phù hợp với PATCH.

challenge icon

Thử thách

Trung bình

Gán mức độ ưu tiên từ 1 (cao) đến 3 (thấp) cho mọi tác vụ. Giữ nguyên mọi thứ bạn đã xây dựng: mọi endpoint tiếp tục hoạt động như trước.

  1. Thêm int Priority = 2 làm thuộc tính cuối cùng của TaskItem. Gán mức độ ưu tiên 1 cho tác vụ 1 và mức độ ưu tiên 3 cho tác vụ 2; tác vụ 3 giữ giá trị mặc định là 2.
  2. Thêm [property: Range(1, 3)] int Priority = 2 làm thuộc tính cuối cùng của TaskInput, rồi truyền input.Priority vào TaskItem mới trong POST và PUT.
  3. Thêm [property: Range(1, 3)] int? Priority vào TaskPatch. Ở đầu PATCH, kiểm tra bản vá bằng Validation.Errors(patch) và trả về Results.ValidationProblem khi phát hiện lỗi. Sao chép mức độ ưu tiên trong with, giống như các trường khác.

Giờ đây, mỗi tác vụ đều có mức độ ưu tiên: { "id": 1, "title": "Write the project brief", "done": false, "priority": 1 }. Mức độ ưu tiên 5 sẽ trả về 400 với "errors": { "priority": ["The field Priority must be between 1 and 3."] }.

Thử ngay: nhấn Chạy: mọi tác vụ trong danh sách đều có mức độ ưu tiên. POST { "title": "Order new chairs" }: mức độ ưu tiên là 2. POST { "title": "Fix the printer", "priority": 5 }: 400. PATCH /api/tasks/3 với { "priority": 1 }: tác vụ 3 trở nên khẩn cấp và giữ nguyên tiêu đề.

Tự làm thử

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, string? sort, HttpResponse response, int page = 1, int pageSize = 10) =>
{
    var errors = new Dictionary<string, string[]>();
    if (sort is not null && sort != "id" && sort != "title")
        errors["sort"] = ["Sort by id or title."];
    if (page < 1)
        errors["page"] = ["Page starts at 1."];
    if (pageSize < 1 || pageSize > 50)
        errors["pageSize"] = ["Page size is 1 to 50."];
    if (errors.Count > 0) return Results.ValidationProblem(errors);

    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));
    if (sort == "title") result = result.OrderBy(t => t.Title);

    var matching = result.ToList();
    response.Headers["X-Total-Count"] = matching.Count.ToString();
    return Results.Ok(matching.Skip((page - 1) * pageSize).Take(pageSize));
});

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);

Tất cả bài học trong REST API