Fix GetContentsByCreator ugly ef query
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using Hutopy.Web.Features.Contents.Data;
|
||||
using System.Text;
|
||||
using Hutopy.Web.Features.Contents.Data;
|
||||
using Hutopy.Web.Features.Contents.Handlers.Models;
|
||||
|
||||
namespace Hutopy.Web.Features.Contents.Handlers;
|
||||
@@ -6,7 +7,7 @@ namespace Hutopy.Web.Features.Contents.Handlers;
|
||||
[PublicAPI]
|
||||
public sealed class GetContentsByCreatorRequest
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public Guid CreatorId { get; set; }
|
||||
[BindFrom("page_size")] public int PageSize { get; set; } = 10;
|
||||
[BindFrom("last_id")] public Guid? LastId { get; set; }
|
||||
}
|
||||
@@ -18,7 +19,7 @@ public class GetContentsByCreatorHandler(
|
||||
{
|
||||
public override void Configure()
|
||||
{
|
||||
Get("/api/contents/creator/{UserId:guid}");
|
||||
Get("/api/contents/creator/{CreatorId:guid}");
|
||||
Options(o => o.WithTags("Contents"));
|
||||
AllowAnonymous();
|
||||
}
|
||||
@@ -27,21 +28,32 @@ public class GetContentsByCreatorHandler(
|
||||
GetContentsByCreatorRequest req,
|
||||
CancellationToken ct)
|
||||
{
|
||||
var query = context
|
||||
.Contents
|
||||
.Where(c => c.CreatedBy == req.UserId);
|
||||
var queryBuilder = new StringBuilder();
|
||||
queryBuilder.AppendLine($"""
|
||||
SELECT content."Id", content."CreatedBy", creator."Name" as CreatedByName, i."Logo" as CreatedByPortraitUrl, content."CreatedAt", content."Title", content."Description", content."Urls"
|
||||
FROM "Content"."Contents" AS content
|
||||
INNER JOIN "Content"."Creators" AS creator ON content."CreatedBy" = creator."Id"
|
||||
LEFT JOIN "Content"."Images" AS i ON creator."Id" = i."CreatorId"
|
||||
WHERE content."CreatedBy" = '{req.CreatorId}'
|
||||
""");
|
||||
|
||||
query = query.OrderByDescending(c => c.CreatedAt);
|
||||
if (req.LastId.HasValue)
|
||||
{
|
||||
queryBuilder.AppendLine($"""AND content."Id" < '{req.LastId.Value}'""");
|
||||
}
|
||||
|
||||
if (req.LastId is not null)
|
||||
query = query.Where(c => c.Id < req.LastId.Value);
|
||||
queryBuilder.AppendLine($"""
|
||||
ORDER BY content."CreatedAt" DESC
|
||||
LIMIT {req.PageSize}
|
||||
""");
|
||||
|
||||
query = query.Take(req.PageSize);
|
||||
|
||||
var posts = await query
|
||||
.Select(x => x.ToResponse())
|
||||
var query = queryBuilder.ToString();
|
||||
|
||||
var results = await context
|
||||
.Database
|
||||
.SqlQueryRaw<ContentModel>(query)
|
||||
.ToListAsync(cancellationToken: ct);
|
||||
|
||||
await SendAsync(posts, cancellation: ct);
|
||||
await SendAsync(results, cancellation: ct);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user