fix(public): distinguish unavailable data from empty results and missing pages
This commit is contained in:
1 parent
db4acbb46e
commit
445ef13846
16 files changed
+608
-169
No files matched your search
@@ -4,6 +4,7 @@ import { getTranslations } from "next-intl/server";
|
||||
import type { CSSProperties } from "react";
|
||||
import { replyToThread } from "@/actions/social";
|
||||
import Link from "@/components/link";
|
||||
import { PublicLoadError } from "@/components/public/load-error";
|
||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { auth } from "@/lib/auth";
|
||||
import {
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
User,
|
||||
} from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { publicReadFailure } from "@/lib/services/public-read";
|
||||
|
||||
type SearchParams = Promise<{ replied?: string; error?: string }>;
|
||||
|
||||
@@ -60,6 +62,8 @@ export default async function GuildForumThreadPage({
|
||||
pinned: number | null;
|
||||
openerId: number | null;
|
||||
} | null = null;
|
||||
let postsFailed = false;
|
||||
let authorsFailed = false;
|
||||
let posts: {
|
||||
id: number;
|
||||
userId: number;
|
||||
@@ -96,9 +100,15 @@ export default async function GuildForumThreadPage({
|
||||
]);
|
||||
guild = guildRow;
|
||||
thread = threadRow;
|
||||
} catch {
|
||||
guild = null;
|
||||
thread = null;
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.thread")(error);
|
||||
return (
|
||||
<main className="page-grid">
|
||||
<ContentCard>
|
||||
<PublicLoadError href={`/guilds/${guildId}/forum/${threadId}`} />
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (!guild || !thread) notFound();
|
||||
@@ -122,7 +132,9 @@ export default async function GuildForumThreadPage({
|
||||
asc(GuildsForumsComments.createdAt),
|
||||
asc(GuildsForumsComments.id),
|
||||
);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.posts")(error);
|
||||
postsFailed = true;
|
||||
posts = [];
|
||||
}
|
||||
|
||||
@@ -137,7 +149,9 @@ export default async function GuildForumThreadPage({
|
||||
.from(User)
|
||||
.where(inArray(User.id, authorIds))
|
||||
: [];
|
||||
} catch {
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.post-authors")(error);
|
||||
authorsFailed = true;
|
||||
users = [];
|
||||
}
|
||||
const usernameById = new Map(users.map((u) => [u.id, u.username]));
|
||||
@@ -195,10 +209,17 @@ export default async function GuildForumThreadPage({
|
||||
<ContentCard
|
||||
icon="📝"
|
||||
title={t("postsTitle")}
|
||||
subtitle={t("postsSubtitle", { count: posts.length })}
|
||||
padded={posts.length === 0}
|
||||
subtitle={
|
||||
postsFailed ? undefined : t("postsSubtitle", { count: posts.length })
|
||||
}
|
||||
padded={posts.length === 0 || authorsFailed}
|
||||
>
|
||||
{posts.length === 0 ? (
|
||||
{authorsFailed && (
|
||||
<PublicLoadError href={`/guilds/${guild.id}/forum/${thread.id}`} />
|
||||
)}
|
||||
{postsFailed ? (
|
||||
<PublicLoadError href={`/guilds/${guild.id}/forum/${thread.id}`} />
|
||||
) : posts.length === 0 ? (
|
||||
<EmptyState icon="📝">{t("postsEmpty")}</EmptyState>
|
||||
) : (
|
||||
<ul
|
||||
|
||||
@@ -3,9 +3,11 @@ import { notFound } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import type { CSSProperties } from "react";
|
||||
import Link from "@/components/link";
|
||||
import { PublicLoadError } from "@/components/public/load-error";
|
||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { db, Guilds, GuildsForumsThreads, User } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { publicReadFailure } from "@/lib/services/public-read";
|
||||
|
||||
type SearchParams = Promise<{ posted?: string }>;
|
||||
|
||||
@@ -49,7 +51,7 @@ export default async function GuildForumPage({
|
||||
const guildId = Number(id);
|
||||
if (!Number.isInteger(guildId) || guildId <= 0) notFound();
|
||||
|
||||
// Guild header (read-only). A DB hiccup degrades to notFound rather than 500.
|
||||
// Missing guilds and unavailable guild data have distinct outcomes.
|
||||
let guild: { id: number; name: string; badge: string } | null = null;
|
||||
try {
|
||||
const [row] = await db
|
||||
@@ -62,13 +64,22 @@ export default async function GuildForumPage({
|
||||
.where(eq(Guilds.id, guildId))
|
||||
.limit(1);
|
||||
guild = row ?? null;
|
||||
} catch {
|
||||
guild = null;
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.forum")(error);
|
||||
return (
|
||||
<main className="page-grid">
|
||||
<ContentCard>
|
||||
<PublicLoadError href={`/guilds/${guildId}/forum`} />
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (!guild) notFound();
|
||||
|
||||
// Threads for this guild. Pinned first, then most-recently active.
|
||||
let threadsFailed = false;
|
||||
let authorsFailed = false;
|
||||
let threads: ThreadRow[] = [];
|
||||
try {
|
||||
threads = await db
|
||||
@@ -95,7 +106,9 @@ export default async function GuildForumPage({
|
||||
desc(GuildsForumsThreads.id),
|
||||
)
|
||||
.limit(100);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.threads")(error);
|
||||
threadsFailed = true;
|
||||
threads = [];
|
||||
}
|
||||
|
||||
@@ -113,7 +126,9 @@ export default async function GuildForumPage({
|
||||
.from(User)
|
||||
.where(inArray(User.id, openerIds))
|
||||
: [];
|
||||
} catch {
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.thread-authors")(error);
|
||||
authorsFailed = true;
|
||||
users = [];
|
||||
}
|
||||
|
||||
@@ -134,7 +149,11 @@ export default async function GuildForumPage({
|
||||
<ContentCard
|
||||
icon="🗣️"
|
||||
title={t("forumTitle", { guild: guild.name || t("unnamedGuild") })}
|
||||
subtitle={`${threads.length} ${threads.length === 1 ? t("threadSingular") : t("threadPlural")}`}
|
||||
subtitle={
|
||||
threadsFailed
|
||||
? undefined
|
||||
: `${threads.length} ${threads.length === 1 ? t("threadSingular") : t("threadPlural")}`
|
||||
}
|
||||
action={
|
||||
<Link
|
||||
href={`/guilds/${guild.id}/forum/new`}
|
||||
@@ -145,8 +164,13 @@ export default async function GuildForumPage({
|
||||
}
|
||||
/>
|
||||
|
||||
<ContentCard padded={threads.length === 0}>
|
||||
{threads.length === 0 ? (
|
||||
<ContentCard padded={threads.length === 0 || authorsFailed}>
|
||||
{authorsFailed && (
|
||||
<PublicLoadError href={`/guilds/${guild.id}/forum`} />
|
||||
)}
|
||||
{threadsFailed ? (
|
||||
<PublicLoadError href={`/guilds/${guild.id}/forum`} />
|
||||
) : threads.length === 0 ? (
|
||||
<EmptyState icon="🗣️">{t("empty")}</EmptyState>
|
||||
) : (
|
||||
<table>
|
||||
|
||||
@@ -2,10 +2,12 @@ import { asc, eq, inArray } from "drizzle-orm";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import Link from "@/components/link";
|
||||
import { PublicLoadError } from "@/components/public/load-error";
|
||||
import { ContentCard, EmptyState, StatBlock } from "@/components/public/ui";
|
||||
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
||||
import { db, Guilds, GuildsMembers, User } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { publicReadFailure } from "@/lib/services/public-read";
|
||||
|
||||
type GuildView = {
|
||||
id: number;
|
||||
@@ -50,14 +52,22 @@ export default async function GuildPage({
|
||||
.where(eq(Guilds.id, guildId))
|
||||
.limit(1);
|
||||
guild = row ?? null;
|
||||
} catch {
|
||||
guild = null;
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.detail")(error);
|
||||
return (
|
||||
<main className="page-grid">
|
||||
<ContentCard>
|
||||
<PublicLoadError href={`/guilds/${guildId}`} />
|
||||
</ContentCard>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
if (!guild) notFound();
|
||||
|
||||
// Members come from guilds_members; there is no relation in the schema, so we
|
||||
// join the users table manually by id.
|
||||
let membersFailed = false;
|
||||
let memberRows: { userId: number; memberSince: number }[] = [];
|
||||
try {
|
||||
memberRows = await db
|
||||
@@ -69,7 +79,9 @@ export default async function GuildPage({
|
||||
.where(eq(GuildsMembers.guildId, guild.id))
|
||||
.orderBy(asc(GuildsMembers.memberSince))
|
||||
.limit(200);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.members")(error);
|
||||
membersFailed = true;
|
||||
memberRows = [];
|
||||
}
|
||||
|
||||
@@ -93,7 +105,9 @@ export default async function GuildPage({
|
||||
.from(User)
|
||||
.where(inArray(User.id, memberIds))
|
||||
: [];
|
||||
} catch {
|
||||
} catch (error) {
|
||||
publicReadFailure("guild.member-users")(error);
|
||||
membersFailed = true;
|
||||
users = [];
|
||||
}
|
||||
|
||||
@@ -159,7 +173,7 @@ export default async function GuildPage({
|
||||
<div className="stat-grid" style={{ marginTop: "1.1rem" }}>
|
||||
<StatBlock
|
||||
icon="👥"
|
||||
value={members.length}
|
||||
value={membersFailed ? "—" : members.length}
|
||||
label={
|
||||
members.length === 1 ? t("memberSingular") : t("memberPlural")
|
||||
}
|
||||
@@ -185,11 +199,18 @@ export default async function GuildPage({
|
||||
<ContentCard
|
||||
icon="👥"
|
||||
title={t("membersTitle")}
|
||||
subtitle={`${members.length} ${members.length === 1 ? t("memberLowerSingular") : t("memberLowerPlural")}`}
|
||||
padded={members.length === 0}
|
||||
subtitle={
|
||||
membersFailed
|
||||
? undefined
|
||||
: `${members.length} ${members.length === 1 ? t("memberLowerSingular") : t("memberLowerPlural")}`
|
||||
}
|
||||
padded={members.length === 0 || membersFailed}
|
||||
>
|
||||
{membersFailed && <PublicLoadError href={`/guilds/${guild.id}`} />}
|
||||
{members.length === 0 ? (
|
||||
<EmptyState icon="👥">{t("noMembers")}</EmptyState>
|
||||
membersFailed ? null : (
|
||||
<EmptyState icon="👥">{t("noMembers")}</EmptyState>
|
||||
)
|
||||
) : (
|
||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
||||
{members.map((m) => (
|
||||
|
||||
@@ -2,9 +2,11 @@ import { desc } from "drizzle-orm";
|
||||
import type { Metadata } from "next";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import Link from "@/components/link";
|
||||
import { PublicLoadError } from "@/components/public/load-error";
|
||||
import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { db, Guilds } from "@/lib/db";
|
||||
import { excerpt } from "@/lib/format";
|
||||
import { publicReadFailure } from "@/lib/services/public-read";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const t = await getTranslations("pages.guilds");
|
||||
@@ -26,7 +28,7 @@ type GuildCard = {
|
||||
badge: string;
|
||||
};
|
||||
|
||||
async function getGuilds(): Promise<GuildCard[]> {
|
||||
async function getGuilds(): Promise<GuildCard[] | null> {
|
||||
try {
|
||||
return await db
|
||||
.select({
|
||||
@@ -38,8 +40,8 @@ async function getGuilds(): Promise<GuildCard[]> {
|
||||
.from(Guilds)
|
||||
.orderBy(desc(Guilds.id))
|
||||
.limit(40);
|
||||
} catch {
|
||||
return [];
|
||||
} catch (error) {
|
||||
return publicReadFailure("guilds")(error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +53,10 @@ export default async function GuildsPage() {
|
||||
<main className="page-grid">
|
||||
<ContentCard icon="🚪" title={t("title")} subtitle={t("subtitle")} />
|
||||
|
||||
<ContentCard padded={guilds.length === 0}>
|
||||
{guilds.length === 0 ? (
|
||||
<ContentCard padded={!guilds?.length}>
|
||||
{guilds === null ? (
|
||||
<PublicLoadError href="/guilds" />
|
||||
) : guilds.length === 0 ? (
|
||||
<EmptyState icon="🚪">{t("empty")}</EmptyState>
|
||||
) : (
|
||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
||||
|
||||
@@ -267,7 +267,11 @@ export default async function MePage({
|
||||
actionLabel={t("allFriends")}
|
||||
bodyClassName="p-5"
|
||||
>
|
||||
{onlineFriends.length === 0 ? (
|
||||
{data.friendsUnavailable ? (
|
||||
<p role="status" className="muted">
|
||||
{t("loadError")}
|
||||
</p>
|
||||
) : onlineFriends.length === 0 ? (
|
||||
<p className="muted">{t("noOnlineFriends")}</p>
|
||||
) : (
|
||||
<div className={styles.friends}>
|
||||
@@ -324,13 +328,22 @@ export default async function MePage({
|
||||
{[
|
||||
{
|
||||
label: t("achievements"),
|
||||
value: format.number(userSettings?.achievementScore ?? 0),
|
||||
value: data.userSettingsUnavailable
|
||||
? "—"
|
||||
: format.number(userSettings?.achievementScore ?? 0),
|
||||
},
|
||||
{
|
||||
label: t("respects"),
|
||||
value: format.number(userSettings?.respectsReceived ?? 0),
|
||||
value: data.userSettingsUnavailable
|
||||
? "—"
|
||||
: format.number(userSettings?.respectsReceived ?? 0),
|
||||
},
|
||||
{
|
||||
label: t("friends"),
|
||||
value: data.friendsUnavailable
|
||||
? "—"
|
||||
: format.number(friendCount),
|
||||
},
|
||||
{ label: t("friends"), value: format.number(friendCount) },
|
||||
{ label: t("lastLogin"), value: date(user.lastLogin) },
|
||||
].map((stat) => (
|
||||
<div key={stat.label}>
|
||||
@@ -400,7 +413,11 @@ export default async function MePage({
|
||||
</details>
|
||||
</SurfaceCard>
|
||||
<SurfaceCard title={t("badges")} bodyClassName="p-5">
|
||||
{badges.length === 0 ? (
|
||||
{data.badgesUnavailable ? (
|
||||
<p role="status" className="muted">
|
||||
{t("loadError")}
|
||||
</p>
|
||||
) : badges.length === 0 ? (
|
||||
<p className="muted">{t("noBadges")}</p>
|
||||
) : (
|
||||
<div className={styles.badges}>
|
||||
|
||||
+94
-69
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
import { desc } from "drizzle-orm";
|
||||
import type { Metadata } from "next";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { PublicLoadError } from "@/components/public/load-error";
|
||||
import {
|
||||
type LightboxPhoto,
|
||||
PhotoLightbox,
|
||||
@@ -9,6 +10,7 @@ import { ContentCard, EmptyState } from "@/components/public/ui";
|
||||
import { cached } from "@/lib/cache";
|
||||
import { CameraWeb, db } from "@/lib/db";
|
||||
import { formatDate } from "@/lib/format-date";
|
||||
import { publicReadFailure } from "@/lib/services/public-read";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const t = await getTranslations("pages.photos");
|
||||
@@ -34,18 +36,18 @@ type Photo = {
|
||||
export default async function PhotosPage() {
|
||||
const t = await getTranslations("pages.photos");
|
||||
|
||||
let photos: Photo[] = [];
|
||||
let photos: Photo[] | null = [];
|
||||
try {
|
||||
photos = await cached("photos:grid", 60_000, async () =>
|
||||
db.select().from(CameraWeb).orderBy(desc(CameraWeb.timestamp)).limit(48),
|
||||
);
|
||||
} catch {
|
||||
photos = [];
|
||||
} catch (error) {
|
||||
photos = publicReadFailure("photos")(error);
|
||||
}
|
||||
|
||||
// Pre-shape for the client lightbox: translate captions server-side so the
|
||||
// client component stays free of i18n/db dependencies.
|
||||
const items: LightboxPhoto[] = photos.map((p) => ({
|
||||
const items: LightboxPhoto[] = (photos ?? []).map((p) => ({
|
||||
id: String(p.id),
|
||||
url: p.url,
|
||||
alt: t("photoAlt", { id: p.userId }),
|
||||
@@ -58,7 +60,9 @@ export default async function PhotosPage() {
|
||||
<ContentCard icon="📸" title={t("title")} subtitle={t("subtitle")} />
|
||||
|
||||
<ContentCard padded={items.length === 0}>
|
||||
{items.length === 0 ? (
|
||||
{photos === null ? (
|
||||
<PublicLoadError href="/photos" />
|
||||
) : items.length === 0 ? (
|
||||
<EmptyState icon="📸">{t("noPhotos")}</EmptyState>
|
||||
) : (
|
||||
<PhotoLightbox photos={items} />
|
||||
|
||||
@@ -2,6 +2,7 @@ import { desc } from "drizzle-orm";
|
||||
import type { Metadata } from "next";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import Link from "@/components/link";
|
||||
import { PublicLoadError } from "@/components/public/load-error";
|
||||
import {
|
||||
ContentCard,
|
||||
EmptyState,
|
||||
@@ -12,6 +13,7 @@ import { CurrencyIcon } from "@/components/shared/currency-icon";
|
||||
import { UserAvatarThumbnail } from "@/components/shared/user-avatar-thumbnail";
|
||||
import { cached } from "@/lib/cache";
|
||||
import { db, User } from "@/lib/db";
|
||||
import { publicReadFailure } from "@/lib/services/public-read";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const t = await getTranslations("pages.rankings");
|
||||
@@ -36,7 +38,7 @@ type TopUser = {
|
||||
|
||||
export default async function RankingsPage() {
|
||||
const t = await getTranslations("pages.rankings");
|
||||
let users: TopUser[] = [];
|
||||
let users: TopUser[] | null = [];
|
||||
try {
|
||||
users = await cached("rankings:top", 60_000, async () =>
|
||||
db
|
||||
@@ -51,16 +53,18 @@ export default async function RankingsPage() {
|
||||
.orderBy(desc(User.credits))
|
||||
.limit(12),
|
||||
);
|
||||
} catch {
|
||||
users = [];
|
||||
} catch (error) {
|
||||
users = publicReadFailure("rankings")(error);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="page-grid">
|
||||
<ContentCard icon="🏆" title={t("title")} subtitle={t("subtitle")} />
|
||||
|
||||
<ContentCard padded={users.length === 0}>
|
||||
{users.length === 0 ? (
|
||||
<ContentCard padded={!users?.length}>
|
||||
{users === null ? (
|
||||
<PublicLoadError href="/rankings" />
|
||||
) : users.length === 0 ? (
|
||||
<EmptyState icon="🏆">{t("emptyState")}</EmptyState>
|
||||
) : (
|
||||
<div className="card-grid sm-2 lg-3" style={{ padding: "1rem" }}>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
"use client";
|
||||
import { useTranslations } from "next-intl";
|
||||
|
||||
export function PublicLoadError({ href }: { href: string }) {
|
||||
const t = useTranslations("publicData");
|
||||
return (
|
||||
<div role="alert" className="flex flex-wrap items-center gap-3">
|
||||
<p>{t("loadError")}</p>
|
||||
<a href={href} className="btn btn-outline">
|
||||
{t("retry")}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,30 @@
|
||||
import { beforeEach, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({ fail: false }));
|
||||
vi.mock("@/lib/logger", () => ({ logger: { error: vi.fn() } }));
|
||||
vi.mock("@/lib/services/news-cache", () => ({
|
||||
cacheNews: async () => {
|
||||
if (state.fail) throw Error("unavailable");
|
||||
return [];
|
||||
},
|
||||
}));
|
||||
vi.mock("@/lib/db", async () => ({ ...(await import("@/db/schema")), db: {} }));
|
||||
|
||||
import { getNewsList } from "./news-list";
|
||||
|
||||
beforeEach(() => {
|
||||
state.fail = false;
|
||||
});
|
||||
it("preserves an empty successful list in strict mode", async () => {
|
||||
expect(await getNewsList(4, { throwOnError: true })).toEqual([]);
|
||||
});
|
||||
it("lets the homepage distinguish a failed news section", async () => {
|
||||
state.fail = true;
|
||||
await expect(getNewsList(4, { throwOnError: true })).rejects.toThrow(
|
||||
"unavailable",
|
||||
);
|
||||
});
|
||||
it("preserves the legacy fallback for other callers", async () => {
|
||||
state.fail = true;
|
||||
expect(await getNewsList(4)).toEqual([]);
|
||||
});
|
||||
@@ -26,12 +26,15 @@ const CACHE_KEY = "news_list";
|
||||
const FETCH_LIMIT = 30;
|
||||
|
||||
/**
|
||||
* Shared, cached news list used by both the homepage and the news archive so
|
||||
* Shared, cached news preview list used by the homepage and other widgets so
|
||||
* a single "news_list" cache entry serves both routes. Returns at most
|
||||
* `limit` rows with `createdAt` normalized to a Date (the cache round-trip
|
||||
* serializes timestamps to ISO strings).
|
||||
*/
|
||||
export async function getNewsList(limit: number): Promise<NewsListItem[]> {
|
||||
export async function getNewsList(
|
||||
limit: number,
|
||||
options: { throwOnError?: boolean } = {},
|
||||
): Promise<NewsListItem[]> {
|
||||
try {
|
||||
const rows = await cacheNews<NewsListRow[]>(CACHE_KEY, TTL_MS, () =>
|
||||
db
|
||||
@@ -62,6 +65,7 @@ export async function getNewsList(limit: number): Promise<NewsListItem[]> {
|
||||
}))
|
||||
.slice(0, limit);
|
||||
} catch (error) {
|
||||
if (options.throwOnError) throw error;
|
||||
logger.error("Public news query failed", { module: "news", error });
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const state = vi.hoisted(() => ({
|
||||
fail: false,
|
||||
friends: [] as { id: number; username: string; online: string }[],
|
||||
}));
|
||||
vi.mock("@/lib/hotel-name", () => ({ resolveHotelName: async () => "Hotel" }));
|
||||
@@ -30,7 +31,8 @@ vi.mock("@/lib/db", async () => {
|
||||
innerJoin: () => chain,
|
||||
orderBy: () => chain,
|
||||
limit: () => chain,
|
||||
catch: () => Promise.resolve(rows),
|
||||
catch: (fallback: () => unknown) =>
|
||||
Promise.resolve(state.fail ? fallback() : rows),
|
||||
// biome-ignore lint/suspicious/noThenProperty: Drizzle query builders are intentionally awaitable.
|
||||
then: (resolve: (value: unknown[]) => unknown) =>
|
||||
Promise.resolve(rows).then(resolve),
|
||||
@@ -46,6 +48,17 @@ import { loadUserDashboard } from "./user-dashboard";
|
||||
describe("dashboard friendships", () => {
|
||||
beforeEach(() => {
|
||||
state.friends = [];
|
||||
state.fail = false;
|
||||
});
|
||||
it("marks unavailable sections instead of presenting them as empty data", async () => {
|
||||
state.fail = true;
|
||||
const data = await loadUserDashboard(1);
|
||||
expect(data).toMatchObject({
|
||||
friendsUnavailable: true,
|
||||
badgesUnavailable: true,
|
||||
userSettingsUnavailable: true,
|
||||
referralsRows: null,
|
||||
});
|
||||
});
|
||||
it("counts each friend once when both directional rows are returned", async () => {
|
||||
const wait = { id: 2, username: "wait", online: "1" };
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { publicReadFailure } from "./public-read";
|
||||
import "server-only";
|
||||
import { and, asc, count, desc, eq, gt, inArray, or } from "drizzle-orm";
|
||||
import {
|
||||
@@ -65,7 +66,7 @@ export async function loadUserDashboard(userId: number) {
|
||||
.from(Rooms)
|
||||
.orderBy(desc(Rooms.id))
|
||||
.limit(6)
|
||||
.catch(() => null),
|
||||
.catch(publicReadFailure("dashboard.rooms")),
|
||||
db
|
||||
.select({
|
||||
badgeCode: UsersBadges.badgeCode,
|
||||
@@ -74,7 +75,7 @@ export async function loadUserDashboard(userId: number) {
|
||||
.from(UsersBadges)
|
||||
.where(and(eq(UsersBadges.userId, userId), gt(UsersBadges.slotId, 0)))
|
||||
.orderBy(asc(UsersBadges.slotId))
|
||||
.catch(() => []),
|
||||
.catch(publicReadFailure("dashboard.badges")),
|
||||
db
|
||||
.select({
|
||||
achievementScore: UsersSettings.achievementScore,
|
||||
@@ -83,19 +84,19 @@ export async function loadUserDashboard(userId: number) {
|
||||
.from(UsersSettings)
|
||||
.where(eq(UsersSettings.userId, userId))
|
||||
.limit(1)
|
||||
.catch(() => []),
|
||||
.catch(publicReadFailure("dashboard.settings")),
|
||||
db
|
||||
.select({ value: count() })
|
||||
.from(MessengerOffline)
|
||||
.where(eq(MessengerOffline.userId, userId))
|
||||
.catch(() => null),
|
||||
.catch(publicReadFailure("dashboard.unread")),
|
||||
db
|
||||
.select({ referralsTotal: UserReferrals.referralsTotal })
|
||||
.from(UserReferrals)
|
||||
.where(eq(UserReferrals.userId, userId))
|
||||
.orderBy(desc(UserReferrals.id))
|
||||
.limit(1)
|
||||
.catch(() => []),
|
||||
.catch(publicReadFailure("dashboard.referrals")),
|
||||
db
|
||||
.select({
|
||||
id: User.id,
|
||||
@@ -124,7 +125,7 @@ export async function loadUserDashboard(userId: number) {
|
||||
eq(MessengerFriendships.userTwoId, userId),
|
||||
),
|
||||
)
|
||||
.catch(() => []),
|
||||
.catch(publicReadFailure("dashboard.friends")),
|
||||
db
|
||||
.select({ type: UsersCurrency.type, amount: UsersCurrency.amount })
|
||||
.from(UsersCurrency)
|
||||
@@ -134,13 +135,13 @@ export async function loadUserDashboard(userId: number) {
|
||||
inArray(UsersCurrency.type, [0, 5]),
|
||||
),
|
||||
)
|
||||
.catch(() => null),
|
||||
.catch(publicReadFailure("dashboard.currency")),
|
||||
]);
|
||||
|
||||
// Each friendship can have two directional rows; expose users, not edges.
|
||||
const uniqueFriends = [
|
||||
...new Map(
|
||||
friends
|
||||
(friends ?? [])
|
||||
.filter((friend) => friend.id !== userId)
|
||||
.map((friend) => [friend.id, friend]),
|
||||
).values(),
|
||||
@@ -155,8 +156,11 @@ export async function loadUserDashboard(userId: number) {
|
||||
currencySettings,
|
||||
alertRaw,
|
||||
recentRooms,
|
||||
badges,
|
||||
userSettingsRows,
|
||||
badges: badges ?? [],
|
||||
badgesUnavailable: badges === null,
|
||||
userSettingsRows: userSettingsRows ?? [],
|
||||
userSettingsUnavailable: userSettingsRows === null,
|
||||
friendsUnavailable: friends === null,
|
||||
friendCountRows: [{ value: uniqueFriends.length }],
|
||||
unreadCountRows,
|
||||
referralsRows,
|
||||
|
||||
Reference in new issue
Block a user