Menu
CoddyTech

레시피 검색

Coddy ASP.NET Core 여정의 Minimal API 섹션에 포함된 레슨. 20개 중 18번째.

이 장에서는 레시피 API에 기능 세 가지를 추가합니다. 각 기능은 이 절에서 배운 내용을 바탕으로 합니다. 첫 번째는 검색입니다. string.Contains는 텍스트 안에서 텍스트를 찾으며 대소문자를 구분합니다. "Pancakes".Contains("pan")의 결과는 false입니다. StringComparison.OrdinalIgnoreCase는 대소문자를 구분하지 않습니다.

var hits = books.Where(b => b.Title.Contains(term, StringComparison.OrdinalIgnoreCase));

/api/recipes/search와 /api/recipes/{id:int}는 충돌하지 않습니다. search는 숫자가 아니며, 라우트에서 고정된 텍스트는 어차피 매개변수보다 우선하기 때문입니다.

challenge icon

챌린지

쉬움

클라이언트는 이름으로 레시피를 검색할 수 있습니다: GET /api/recipes/search?q=soup. 이전 레슨에서 작성한 내용은 모두 유지하세요.

  1. Program.cs에서 GET /api/recipes/search를 매핑하세요. 람다는 string? q를 인수로 받습니다.
  2. string.IsNullOrWhiteSpace(q)인 경우 Results.BadRequest(new { error = "Add ?q= to search" })를 반환하세요.
  3. 그렇지 않으면 대소문자를 구분하지 않고 Name에 q가 포함된 레시피를 recipes의 순서대로 Results.Ok(...)에 담아 반환하세요.

직접 해보기: ‘실행’을 누르세요. GET /api/recipes/search?q=soup의 응답은 Tomato Soup와 Lentil Soup입니다. ?q=PAN을 보내세요: Pancakes. ?q=pizza를 보내세요: []. 쿼리 없이 GET /api/recipes/search를 보내세요: 상태 코드 400과 {"error":"Add ?q= to search"}.

직접 해보기

using Microsoft.AspNetCore.Http.HttpResults;

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

app.Use(async (context, next) =>
{
    await next();
    app.Logger.LogInformation("{Method} {Path} -> {Status}",
        context.Request.Method, context.Request.Path, context.Response.StatusCode);
});

app.Use(async (context, next) =>
{
    context.Response.Headers["X-Api-Version"] = "1";
    await next();
});

app.Use(async (context, next) =>
{
    if (context.Request.Path.StartsWithSegments("/recipes"))
    {
        context.Response.Redirect("/api" + context.Request.Path + context.Request.QueryString, permanent: true);
        return;
    }
    await next();
});

app.UseStaticFiles();

var recipes = new List<Recipe>
{
    new(1, "Tomato Soup", "soup", 25),
    new(2, "Pancakes", "breakfast", 15),
    new(3, "Lentil Soup", "soup", 40),
};
var nextId = 4;
var favoriteIds = new List<int>();

app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
    recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id, ILogger<Program> logger) =>
{
    var recipe = recipes.FirstOrDefault(r => r.Id == id);
    if (recipe is null)
    {
        logger.LogWarning("Recipe {Id} was not found", id);
        return Results.NotFound(new { error = $"Recipe {id} not found" });
    }
    return Results.Ok(recipe);
});

app.MapPost("/api/recipes", (NewRecipe input, ILogger<Program> logger) =>
{
    if (string.IsNullOrWhiteSpace(input.Name))
        return Results.BadRequest(new { error = "Name is required" });
    if (input.Minutes <= 0)
        return Results.BadRequest(new { error = "Minutes must be more than 0" });
    var recipe = new Recipe(nextId++, input.Name, input.Category, input.Minutes);
    recipes.Add(recipe);
    logger.LogInformation("Added recipe {Id}: {Name}", recipe.Id, recipe.Name);
    return Results.Created($"/api/recipes/{recipe.Id}", recipe);
});

app.MapPut("/api/recipes/{id:int}", (int id, NewRecipe input) =>
{
    var index = recipes.FindIndex(r => r.Id == id);
    if (index == -1)
        return Results.NotFound(new { error = $"Recipe {id} not found" });
    var recipe = new Recipe(id, input.Name, input.Category, input.Minutes);
    recipes[index] = recipe;
    return Results.Ok(recipe);
});

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

var favorites = app.MapGroup("/api/favorites");
favorites.MapGet("/", () => recipes.Where(r => favoriteIds.Contains(r.Id)));
favorites.MapPost("/{id:int}", (int id) =>
{
    if (!recipes.Any(r => r.Id == id))
        return Results.NotFound(new { error = $"Recipe {id} not found" });
    if (!favoriteIds.Contains(id))
        favoriteIds.Add(id);
    return Results.NoContent();
});
favorites.MapDelete("/{id:int}", (int id) =>
{
    favoriteIds.Remove(id);
    return Results.NoContent();
});

app.Run();

Minimal API의 모든 레슨