Sort stories by most recently updated page

This commit is contained in:
Riccardo Giorato
2025-12-26 20:02:57 +01:00
parent f3c1398bd2
commit 5917508175
2 changed files with 114 additions and 69 deletions
+20 -5
View File
@@ -2,7 +2,7 @@ import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { db } from "@/lib/db";
import { stories, pages } from "@/lib/schema";
import { eq } from "drizzle-orm";
import { eq, desc, sql } from "drizzle-orm";
export async function GET() {
try {
@@ -15,7 +15,7 @@ export async function GET() {
);
}
// Get all stories for the user with their first page
// Get all stories for the user with their pages
const userStories = await db
.select({
id: stories.id,
@@ -24,13 +24,14 @@ export async function GET() {
createdAt: stories.createdAt,
pageCount: pages.pageNumber,
coverImage: pages.generatedImageUrl,
pageCreatedAt: pages.createdAt,
pageUpdatedAt: pages.updatedAt,
})
.from(stories)
.leftJoin(pages, eq(stories.id, pages.storyId))
.where(eq(stories.userId, userId))
.orderBy(stories.createdAt);
.where(eq(stories.userId, userId));
// Group by story and find the max page number and first page image
// Group by story and find the max page number, first page image, and most recent update
const storyMap = new Map();
userStories.forEach((row) => {
@@ -43,6 +44,7 @@ export async function GET() {
createdAt: row.createdAt,
pageCount: 0,
coverImage: null,
lastUpdated: row.createdAt, // Default to story creation date
});
}
@@ -53,10 +55,23 @@ export async function GET() {
if (row.pageCount === 1 && row.coverImage) {
story.coverImage = row.coverImage;
}
// Track the most recent page update
if (row.pageUpdatedAt && row.pageUpdatedAt > story.lastUpdated) {
story.lastUpdated = row.pageUpdatedAt;
} else if (row.pageCreatedAt && row.pageCreatedAt > story.lastUpdated) {
story.lastUpdated = row.pageCreatedAt;
}
});
const storiesWithCovers = Array.from(storyMap.values());
// Sort by most recently updated (stories with newest pages first)
storiesWithCovers.sort((a, b) => {
const aTime = new Date(a.lastUpdated).getTime();
const bTime = new Date(b.lastUpdated).getTime();
return bTime - aTime; // Most recent first
});
return NextResponse.json({
stories: storiesWithCovers
});