Path: redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/ProductsController.cs
Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Templates/templates/redb-bff/RedbBff.Backend/Controllers/ProductsController.cs
----
using System.Globalization;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Route.Controllers.Attributes;
using RedbBff.Backend.Props;
using RedbBff.Models;
namespace RedbBff.Backend.Controllers;
///
/// The products. Attributes route the request: [HttpGet("{id}")] binds the path segment to the
/// id parameter, [FromQuery] a query parameter, [FromBody] the JSON body. The return
/// value is the JSON answer; null answers 204.
///
[Route("/api/products")]
public sealed class ProductsController : ApiController
{
public const int PageSize = 10;
/// GET /api/products?search=&inStock=&sort=&page=. Search, sorting and paging run in the database.
[HttpGet]
public async Task List(
[FromQuery("search")] string? search,
[FromQuery("inStock")] string? inStock,
[FromQuery("sort")] string? sort,
[FromQuery("page")] string? page)
{
var redb = Redb;
var term = search?.Trim();
var inStockOnly = inStock == "true";
// The filter is built from scratch for the count and for the page, so the two queries share no state.
IRedbQueryable Filtered()
{
var query = redb.Query();
// Name is the object's own field, so it is filtered with WhereRedb; Props fields use Where.
if (!string.IsNullOrEmpty(term))
query = query.WhereRedb(x => x.Name.Contains(term));
if (inStockOnly)
query = query.Where(x => x.InStock);
return query;
}
var total = await Filtered().CountAsync();
var pageCount = Math.Max(1, (total + PageSize - 1) / PageSize);
var number = Math.Clamp(int.TryParse(page, CultureInfo.InvariantCulture, out var p) ? p : 1, 1, pageCount);
IRedbQueryable sorted = sort switch
{
"price" => Filtered().OrderBy(x => x.Price),
"-price" => Filtered().OrderByDescending(x => x.Price),
"category" => Filtered().OrderBy(x => x.Category),
_ => Filtered().OrderByRedb(x => x.Name),
};
var items = await sorted.Skip((number - 1) * PageSize).Take(PageSize).ToListAsync();
return new ProductPage { Items = items.Select(ToDto).ToList(), Total = total, Page = number, PageSize = PageSize };
}
[HttpGet("{id}")]
public async Task