Degrade gracefully when galleries API returns 5xx (BIT-33535)
ci / typescript (push) Skipped
ci / rust (push) Skipped
ci / rust (pull_request) Successful in 5m30s
ci / typescript (pull_request) Successful in 11m54s

The site home page SSR fetches galleries, latest, and popular in
Promise.all. When the API has a transient Postgres outage, the
galleries endpoint returns 500 and the site rethrows it, tripping
the Error Loop reporter. Wrap non-critical fetches (galleries,
latest, popular) with a safe() helper that returns empty data on
server errors while keeping 404 -> NotFound and 500 from getSite()
as real errors.

Paperclip-Issue: BIT-33535
This commit is contained in:
paula-alves committed 2026-12-04 09:59:56 +00:00
1 parent 23c2f29a05
commit 932b9db233
3 files changed
+92 -10

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
import type { LatestPhoto, PopularGallery, PublicGallerySummary } from "@photoreport/contracts";
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
function safe<T>(p: Promise<T>, fallback: T): Promise<T> {
return p.catch((err) => {
if (err instanceof NotFound) throw err;
return fallback;
});
}
export async function load(q: string, sport: string) {
const filtered = !!(q || sport);
try {
return await Promise.all([
getSite(),
safe(getGalleries({ q, sport }), { galleries: [] as PublicGallerySummary[], sports: [] as string[] }),
filtered ? Promise.resolve([] as LatestPhoto[]) : safe(getLatest(), [] as LatestPhoto[]),
filtered ? Promise.resolve([] as PopularGallery[]) : safe(getPopular(), [] as PopularGallery[]),
]);
} catch (err) {
if (err instanceof NotFound) return null;
throw err;
}
}
+67
View File
@@ -0,0 +1,67 @@
import { describe, expect, it, vi, afterEach, beforeEach } from "vitest";
vi.mock("next/headers", () => ({
headers: () => Promise.resolve(new Headers({ host: "test.local" })),
cookies: () => Promise.resolve({ get: () => undefined }),
}));
const { load } = await import("./home-data");
const siteBody = {
id: "s1",
domain: "test.local",
skin: "photoreport",
name: "Test",
settings: {},
};
function mockFetch(responses: Record<string, { status: number; body: unknown }>) {
global.fetch = vi.fn(async (url: string | URL) => {
const path = new URL(url).pathname;
const match = Object.entries(responses).find(([key]) => path.includes(key));
if (!match) return new Response("{}", { status: 404 });
const { status, body } = match[1];
return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
}) as typeof fetch;
}
describe("home load — graceful degradation", () => {
const originalFetch = global.fetch;
afterEach(() => {
global.fetch = originalFetch;
});
it("returns empty galleries when the galleries API returns 500", async () => {
mockFetch({
"/v1/public/site": { status: 200, body: siteBody },
"/v1/public/galleries": { status: 500, body: {} },
"/v1/public/latest": { status: 200, body: { photos: [] } },
"/v1/public/popular": { status: 200, body: { galleries: [] } },
});
const result = await load("", "");
expect(result).not.toBeNull();
if (!result) return;
const [, galleries] = result;
expect(galleries.galleries).toEqual([]);
expect(galleries.sports).toEqual([]);
});
it("returns null when the site API returns 404 (unconfigured shop)", async () => {
mockFetch({
"/v1/public/site": { status: 404, body: {} },
});
const result = await load("", "");
expect(result).toBeNull();
});
it("throws when the site API returns 500 (real error)", async () => {
mockFetch({
"/v1/public/site": { status: 500, body: {} },
});
await expect(load("", "")).rejects.toThrow("/v1/public/site: 500");
});
});
+1 -10
View File
@@ -1,22 +1,13 @@
import Link from "next/link";
import { getGalleries, getLatest, getPopular, getSite, NotFound } from "../lib/api";
import { eventTitle, longDate } from "../lib/format";
import { load } from "./home-data";
export const dynamic = "force-dynamic";
const SPORT_NAMES: Record<string, string> = { andebol: "Andebol", futebol: "Futebol", futsal: "Futsal", basquetebol: "Basquetebol", voleibol: "Voleibol", hoquei: "Hóquei", "hóquei em patins": "Hóquei em patins", rugby: "Râguebi", atletismo: "Atletismo" };
const sportName = (s: string) => SPORT_NAMES[s] ?? s.charAt(0).toUpperCase() + s.slice(1);
async function load(q: string, sport: string) {
try {
const filtered = !!(q || sport);
return await Promise.all([getSite(), getGalleries({ q, sport }), filtered ? Promise.resolve([]) : getLatest(), filtered ? Promise.resolve([]) : getPopular()]);
} catch (err) {
if (err instanceof NotFound) return null;
throw err;
}
}
/** Home: search, sport shortcuts, the photos that just arrived, then the galleries. */
export default async function Home({ searchParams }: { searchParams: Promise<{ q?: string; desporto?: string }> }) {
const params = await searchParams;