fix(public): distinguish unavailable data from empty results and missing pages
CI / check (push) Successful in 56s
CI / deploy (push) Successful in 1m30s
CI / publish-container (push) Successful in 44s

This commit is contained in:
Simo committed 2026-09-11 00:39:53 +02:00
1 parent db4acbb46e
commit 445ef13846
16 files changed
+608 -169

No files matched your search

+30
View File
@@ -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([]);
});
+6 -2
View File
@@ -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 [];
}
+14 -1
View File
@@ -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" };
+14 -10
View File
@@ -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,