fix(news): preserve recoverable reads and verify publication against real services
This commit is contained in:
1 parent
8abfe352ef
commit
f7b9b55700
33 files changed
+1377
-220
No files matched your search
@@ -1,4 +1,3 @@
|
||||
import { and, asc, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import type { Metadata } from "next";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
@@ -10,23 +9,22 @@ import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { SanitizedHtml } from "@/components/shared/sanitized-html";
|
||||
import { articleSlug } from "@/lib/article-input";
|
||||
import { auth } from "@/lib/auth";
|
||||
import {
|
||||
db,
|
||||
User,
|
||||
WebsiteArticleComments,
|
||||
WebsiteArticleReactions,
|
||||
WebsiteArticles,
|
||||
} from "@/lib/db";
|
||||
import { excerpt } from "@/lib/format";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { withPublicPagePerformance } from "@/lib/public-page-performance";
|
||||
import { sanitize } from "@/lib/sanitize";
|
||||
import { cacheNews } from "@/lib/services/news-cache";
|
||||
import {
|
||||
getArticleComments,
|
||||
getArticleReactions,
|
||||
getPublishedArticle,
|
||||
} from "@/lib/services/news-detail";
|
||||
|
||||
type SearchParams = Promise<{
|
||||
comment?: string;
|
||||
reaction?: string;
|
||||
error?: string;
|
||||
commentsPage?: string;
|
||||
}>;
|
||||
|
||||
function feedbackStyle(tone: "success" | "error"): CSSProperties {
|
||||
@@ -52,24 +50,10 @@ export async function generateMetadata({
|
||||
}): Promise<Metadata> {
|
||||
const appUrl = process.env.APP_URL ?? "http://localhost:3000";
|
||||
const slug = articleSlug((await params).slug);
|
||||
const [article] = await db
|
||||
.select({
|
||||
title: WebsiteArticles.title,
|
||||
shortStory: WebsiteArticles.shortStory,
|
||||
})
|
||||
.from(WebsiteArticles)
|
||||
.where(
|
||||
and(
|
||||
eq(WebsiteArticles.slug, slug),
|
||||
eq(WebsiteArticles.status, "published"),
|
||||
or(
|
||||
sql`${WebsiteArticles.publishAt} IS NULL`,
|
||||
sql`${WebsiteArticles.publishAt} <= NOW()`,
|
||||
),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
.catch(() => []);
|
||||
const article = await getPublishedArticle(slug).catch(() => {
|
||||
logger.error("Public article metadata failed", { module: "news" });
|
||||
return null;
|
||||
});
|
||||
if (!article) return { title: "Article" };
|
||||
return {
|
||||
title: article.title,
|
||||
@@ -101,36 +85,28 @@ async function ArticlePage({
|
||||
searchParams: SearchParams;
|
||||
}) {
|
||||
const slug = articleSlug((await params).slug);
|
||||
const { comment, reaction, error } = await searchParams;
|
||||
const { comment, reaction, error, commentsPage } = await searchParams;
|
||||
const t = await getTranslations("pages.article");
|
||||
|
||||
const article = await cacheNews(`article:slug:${slug}`, 60_000, async () => {
|
||||
const [row] = await db
|
||||
.select({
|
||||
id: WebsiteArticles.id,
|
||||
slug: WebsiteArticles.slug,
|
||||
title: WebsiteArticles.title,
|
||||
shortStory: WebsiteArticles.shortStory,
|
||||
fullStory: WebsiteArticles.fullStory,
|
||||
image: WebsiteArticles.image,
|
||||
createdAt: WebsiteArticles.createdAt,
|
||||
updatedAt: WebsiteArticles.updatedAt,
|
||||
})
|
||||
.from(WebsiteArticles)
|
||||
.where(
|
||||
and(
|
||||
eq(WebsiteArticles.slug, slug),
|
||||
eq(WebsiteArticles.status, "published"),
|
||||
or(
|
||||
sql`${WebsiteArticles.publishAt} IS NULL`,
|
||||
sql`${WebsiteArticles.publishAt} <= NOW()`,
|
||||
),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
.catch(() => []);
|
||||
return row ?? null;
|
||||
});
|
||||
let article: Awaited<ReturnType<typeof getPublishedArticle>>;
|
||||
try {
|
||||
article = await getPublishedArticle(slug);
|
||||
} catch {
|
||||
logger.error("Public article lookup failed", { module: "news" });
|
||||
return (
|
||||
<main className="page-grid">
|
||||
<ContentCard icon="📰" title={t("loadError")}>
|
||||
<p role="alert">{t("loadError")}</p>
|
||||
<a
|
||||
className="btn btn-outline"
|
||||
href={`/news/${encodeURIComponent(slug)}`}
|
||||
>
|
||||
{t("retry")}
|
||||
</a>
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
if (!article) notFound();
|
||||
|
||||
const articleId = article.id;
|
||||
@@ -139,60 +115,33 @@ async function ArticlePage({
|
||||
const loggedIn = Boolean(session?.user?.id);
|
||||
const sessionUserId = session?.user?.id ? Number(session.user.id) : null;
|
||||
|
||||
// Reaction counts grouped by reaction type for this article, plus the
|
||||
// signed-in user's currently-active reaction (so its button reads as pressed).
|
||||
let reactionCounts = new Map<string, number>();
|
||||
let myReaction: string | null = null;
|
||||
try {
|
||||
const rows = await db
|
||||
.select({
|
||||
reaction: WebsiteArticleReactions.reaction,
|
||||
userId: WebsiteArticleReactions.userId,
|
||||
})
|
||||
.from(WebsiteArticleReactions)
|
||||
.where(
|
||||
and(
|
||||
eq(WebsiteArticleReactions.articleId, articleId),
|
||||
eq(WebsiteArticleReactions.active, true),
|
||||
),
|
||||
);
|
||||
for (const r of rows) {
|
||||
reactionCounts.set(r.reaction, (reactionCounts.get(r.reaction) ?? 0) + 1);
|
||||
if (sessionUserId !== null && r.userId === sessionUserId)
|
||||
myReaction = r.reaction;
|
||||
}
|
||||
} catch {
|
||||
reactionCounts = new Map();
|
||||
myReaction = null;
|
||||
}
|
||||
|
||||
// Comments for this article (oldest first).
|
||||
let comments: (typeof WebsiteArticleComments.$inferSelect)[] = [];
|
||||
try {
|
||||
comments = await db
|
||||
.select()
|
||||
.from(WebsiteArticleComments)
|
||||
.where(eq(WebsiteArticleComments.articleId, articleId))
|
||||
.orderBy(asc(WebsiteArticleComments.createdAt))
|
||||
.limit(200);
|
||||
} catch {
|
||||
comments = [];
|
||||
}
|
||||
|
||||
// Resolve usernames for the commenters (userId is the emulator users.id, Int).
|
||||
const commenterIds = Array.from(new Set(comments.map((c) => c.userId)));
|
||||
let usernameById = new Map<number, string>();
|
||||
if (commenterIds.length > 0) {
|
||||
try {
|
||||
const users = await db
|
||||
.select({ id: User.id, username: User.username })
|
||||
.from(User)
|
||||
.where(inArray(User.id, commenterIds));
|
||||
usernameById = new Map(users.map((u) => [u.id, u.username]));
|
||||
} catch {
|
||||
usernameById = new Map();
|
||||
}
|
||||
}
|
||||
const requestedPage =
|
||||
comment === "posted" && !commentsPage ? "last" : Number(commentsPage ?? 1);
|
||||
const [reactions, commentsResult] = await Promise.all([
|
||||
getArticleReactions(articleId, sessionUserId).catch(() => {
|
||||
logger.error("Public article reactions failed", {
|
||||
module: "news",
|
||||
articleId: String(articleId),
|
||||
});
|
||||
return null;
|
||||
}),
|
||||
getArticleComments(articleId, requestedPage).catch(() => {
|
||||
logger.error("Public article comments failed", {
|
||||
module: "news",
|
||||
articleId: String(articleId),
|
||||
});
|
||||
return null;
|
||||
}),
|
||||
]);
|
||||
const reactionCounts = reactions?.counts ?? new Map<string, number>();
|
||||
const myReaction = reactions?.myReaction ?? null;
|
||||
const comments = commentsResult?.rows ?? [];
|
||||
const articleHref = `/news/${encodeURIComponent(slug)}`;
|
||||
const commentsHref = (page: number) =>
|
||||
`${articleHref}?commentsPage=${page}#comments`;
|
||||
const retryHref = commentsPage
|
||||
? `${articleHref}?${new URLSearchParams({ commentsPage })}`
|
||||
: articleHref;
|
||||
|
||||
const errorMessage =
|
||||
error === "empty"
|
||||
@@ -231,7 +180,9 @@ async function ArticlePage({
|
||||
icon="📰"
|
||||
title={article.title}
|
||||
subtitle={
|
||||
article.createdAt ? formatDate(article.createdAt, "date") : undefined
|
||||
(article.publishAt ?? article.createdAt)
|
||||
? formatDate(article.publishAt ?? article.createdAt, "date")
|
||||
: undefined
|
||||
}
|
||||
action={
|
||||
<Link className="btn btn-outline" href="/news">
|
||||
@@ -261,7 +212,14 @@ async function ArticlePage({
|
||||
title={t("reactionsTitle")}
|
||||
subtitle={t("reactionsSubtitle")}
|
||||
>
|
||||
{loggedIn ? (
|
||||
{!reactions ? (
|
||||
<div role="alert">
|
||||
<p>{t("reactionsUnavailable")}</p>
|
||||
<a className="btn btn-outline" href={retryHref}>
|
||||
{t("retry")}
|
||||
</a>
|
||||
</div>
|
||||
) : loggedIn ? (
|
||||
<div style={{ display: "flex", gap: "0.5rem", flexWrap: "wrap" }}>
|
||||
{REACTIONS.map((r) => {
|
||||
const active = myReaction === r.key;
|
||||
@@ -331,80 +289,131 @@ async function ArticlePage({
|
||||
</ContentCard>
|
||||
|
||||
{/* ── Comments ──────────────────────────────────────────── */}
|
||||
<ContentCard
|
||||
icon="🗨️"
|
||||
title={t("commentsTitle")}
|
||||
subtitle={
|
||||
comments.length > 0
|
||||
? t("commentsCount", { count: comments.length })
|
||||
: t("commentsSubtitle")
|
||||
}
|
||||
>
|
||||
{comments.length === 0 ? (
|
||||
<EmptyState icon="🗨️">{t("noComments")}</EmptyState>
|
||||
) : (
|
||||
<div className="grid" style={{ marginBottom: "1.5rem" }}>
|
||||
{comments.map((c) => {
|
||||
const name = usernameById.get(c.userId);
|
||||
return (
|
||||
<article key={String(c.id)} className="card">
|
||||
<p
|
||||
className="muted"
|
||||
style={{ marginTop: 0, marginBottom: "0.35rem" }}
|
||||
>
|
||||
{name ? (
|
||||
<Link href={`/u/${name}`}>{name}</Link>
|
||||
) : (
|
||||
<span>{t("userNumber", { id: c.userId })}</span>
|
||||
)}
|
||||
{c.createdAt ? (
|
||||
<span> · {formatDate(c.createdAt, "date", "")}</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p style={{ margin: 0, whiteSpace: "pre-wrap" }}>
|
||||
{c.comment}
|
||||
</p>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loggedIn ? (
|
||||
<form action={postComment} className="card">
|
||||
<input type="hidden" name="articleId" value={String(articleId)} />
|
||||
<input type="hidden" name="slug" value={slug} />
|
||||
<label
|
||||
htmlFor="comment"
|
||||
style={{
|
||||
display: "block",
|
||||
fontWeight: 700,
|
||||
marginBottom: "0.5rem",
|
||||
}}
|
||||
>
|
||||
{t("addComment")}
|
||||
</label>
|
||||
<textarea
|
||||
id="comment"
|
||||
name="comment"
|
||||
required
|
||||
maxLength={255}
|
||||
rows={3}
|
||||
placeholder={t("commentPlaceholder")}
|
||||
style={{ width: "100%", resize: "vertical" }}
|
||||
/>
|
||||
<div style={{ marginTop: "0.75rem" }}>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("postComment")}
|
||||
</button>
|
||||
<section id="comments" aria-label={t("commentsTitle")}>
|
||||
<ContentCard
|
||||
icon="🗨️"
|
||||
title={t("commentsTitle")}
|
||||
subtitle={
|
||||
commentsResult && commentsResult.total > 0
|
||||
? t("commentsCount", { count: commentsResult.total })
|
||||
: t("commentsSubtitle")
|
||||
}
|
||||
>
|
||||
{!commentsResult ? (
|
||||
<div role="alert">
|
||||
<p>{t("commentsUnavailable")}</p>
|
||||
<a className="btn btn-outline" href={`${retryHref}#comments`}>
|
||||
{t("retry")}
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<p className="muted">
|
||||
<Link href="/login">{t("logIn")}</Link> {t("toComment")}
|
||||
</p>
|
||||
)}
|
||||
</ContentCard>
|
||||
) : comments.length === 0 ? (
|
||||
<EmptyState icon="🗨️">{t("noComments")}</EmptyState>
|
||||
) : (
|
||||
<div className="grid" style={{ marginBottom: "1.5rem" }}>
|
||||
{comments.map((c) => {
|
||||
const name = c.username;
|
||||
return (
|
||||
<article key={String(c.id)} className="card">
|
||||
<p
|
||||
className="muted"
|
||||
style={{ marginTop: 0, marginBottom: "0.35rem" }}
|
||||
>
|
||||
{name ? (
|
||||
<Link href={`/u/${name}`}>{name}</Link>
|
||||
) : (
|
||||
<span>{t("userNumber", { id: c.userId })}</span>
|
||||
)}
|
||||
{c.createdAt ? (
|
||||
<span> · {formatDate(c.createdAt, "date", "")}</span>
|
||||
) : null}
|
||||
</p>
|
||||
<p
|
||||
style={{
|
||||
margin: 0,
|
||||
whiteSpace: "pre-wrap",
|
||||
overflowWrap: "anywhere",
|
||||
}}
|
||||
>
|
||||
{c.comment}
|
||||
</p>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{commentsResult && commentsResult.lastPage > 1 ? (
|
||||
<nav
|
||||
aria-label={t("commentsPagination")}
|
||||
className="flex flex-wrap items-center justify-between gap-3"
|
||||
style={{ marginBottom: "1rem" }}
|
||||
>
|
||||
{commentsResult.page > 1 ? (
|
||||
<Link
|
||||
className="btn btn-outline"
|
||||
href={commentsHref(commentsResult.page - 1)}
|
||||
>
|
||||
{t("previous")}
|
||||
</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
<span>
|
||||
{t("commentsPageSummary", {
|
||||
page: commentsResult.page,
|
||||
pages: commentsResult.lastPage,
|
||||
total: commentsResult.total,
|
||||
})}
|
||||
</span>
|
||||
{commentsResult.page < commentsResult.lastPage ? (
|
||||
<Link
|
||||
className="btn btn-outline"
|
||||
href={commentsHref(commentsResult.page + 1)}
|
||||
>
|
||||
{t("next")}
|
||||
</Link>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
</nav>
|
||||
) : null}
|
||||
|
||||
{loggedIn ? (
|
||||
<form action={postComment} className="card">
|
||||
<input type="hidden" name="articleId" value={String(articleId)} />
|
||||
<input type="hidden" name="slug" value={slug} />
|
||||
<label
|
||||
htmlFor="comment"
|
||||
style={{
|
||||
display: "block",
|
||||
fontWeight: 700,
|
||||
marginBottom: "0.5rem",
|
||||
}}
|
||||
>
|
||||
{t("addComment")}
|
||||
</label>
|
||||
<textarea
|
||||
id="comment"
|
||||
name="comment"
|
||||
required
|
||||
maxLength={255}
|
||||
rows={3}
|
||||
placeholder={t("commentPlaceholder")}
|
||||
style={{ width: "100%", resize: "vertical" }}
|
||||
/>
|
||||
<div style={{ marginTop: "0.75rem" }}>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{t("postComment")}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<p className="muted">
|
||||
<Link href="/login">{t("logIn")}</Link> {t("toComment")}
|
||||
</p>
|
||||
)}
|
||||
</ContentCard>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user