Replace API route handlers with server actions across the app

- Delete 10 API routes (stats, system-health, update-check, jobs/trigger,
  backup/restore, person, titles import/resolve, registration/status) and
  move logic into server actions in lib/actions/settings.ts and
  lib/actions/watchlist.ts
- Refactor SystemHealthCards to accept initialData prop and hydrate Jotai
  atoms via useHydrateAtoms; replace useSystemHealth SWR hook with a
  lightweight useSystemHealthRefresh that calls getSystemHealthAction
- Convert BackupRestoreSection to use restoreBackupAction + useTransition
  instead of a raw fetch call
- Split SystemStatusCard, BackgroundJobsCard, and StorageCard into
  standalone components reading from systemHealthDataAtom
- Make SetupPage async with connection() to opt into dynamic rendering
This commit is contained in:
2026-03-06 17:31:14 -05:00
parent 73b07f5ff6
commit 8d8c49a7f0
21 changed files with 396 additions and 630 deletions
+55 -1
View File
@@ -3,7 +3,7 @@
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { requireAdmin, requireSession } from "@/lib/auth/session";
import { type BackupFrequency, rescheduleBackup } from "@/lib/cron";
import { type BackupFrequency, rescheduleBackup, triggerJob } from "@/lib/cron";
import { db } from "@/lib/db/client";
import { integrations } from "@/lib/db/schema";
import {
@@ -11,8 +11,17 @@ import {
createBackup,
deleteBackup,
listBackups,
restoreFromBackup,
} from "@/lib/services/backup";
import { getSetting, setSetting } from "@/lib/services/settings";
import {
getSystemHealth,
type SystemHealthData,
} from "@/lib/services/system-health";
import {
getCachedUpdateCheck,
type UpdateCheckResult,
} from "@/lib/services/update-check";
const providerSchema = z.enum(["plex", "jellyfin", "emby", "sonarr", "radarr"]);
@@ -207,3 +216,48 @@ export async function setBackupScheduleAction(
setSetting("backupScheduleDow", String(parsed.dayOfWeek));
rescheduleBackup();
}
// --- System health actions ---
export async function getSystemHealthAction(): Promise<SystemHealthData> {
await requireAdmin();
return getSystemHealth();
}
// --- Job trigger action ---
export async function triggerJobAction(
jobName: string,
): Promise<{ ok: boolean }> {
await requireAdmin();
if (!jobName || typeof jobName !== "string") {
throw new Error("Missing job name");
}
const triggered = await triggerJob(jobName);
if (!triggered) throw new Error("Job not found");
return { ok: true };
}
// --- Backup restore action ---
const MAX_RESTORE_SIZE = 500 * 1024 * 1024; // 500MB
export async function restoreBackupAction(formData: FormData): Promise<void> {
await requireAdmin();
const file = formData.get("file") as File | null;
if (!file) throw new Error("No file provided");
if (file.size > MAX_RESTORE_SIZE) throw new Error("File too large");
const buffer = Buffer.from(await file.arrayBuffer());
await restoreFromBackup(buffer);
}
// --- Update check action ---
export async function getUpdateCheckAction(): Promise<UpdateCheckResult | null> {
try {
await requireAdmin();
return getCachedUpdateCheck();
} catch {
return null;
}
}
+23
View File
@@ -1,9 +1,16 @@
"use server";
import { and, eq } from "drizzle-orm";
import { z } from "zod";
import { getSession, requireSession } from "@/lib/auth/session";
import { db } from "@/lib/db/client";
import { userTitleStatus } from "@/lib/db/schema";
import {
getWatchCount,
getWatchHistory,
type HistoryBucket,
type TimePeriod,
} from "@/lib/services/discovery";
import { importTitle } from "@/lib/services/metadata";
import {
getEpisodeProgressByTmdbIds,
@@ -55,3 +62,19 @@ export async function quickAddToWatchlist(
setTitleStatus(userId, title.id, "watchlist");
return { success: true, titleId: title.id, alreadyAdded: false };
}
const statsSchema = z.object({
type: z.enum(["movies", "episodes"]),
period: z.enum(["today", "this_week", "this_month", "this_year"]),
});
export async function getStatsAction(
type: "movies" | "episodes",
period: TimePeriod,
): Promise<{ count: number; history: HistoryBucket[] }> {
const session = await requireSession();
const parsed = statsSchema.parse({ type, period });
const count = getWatchCount(session.user.id, parsed.type, parsed.period);
const history = getWatchHistory(session.user.id, parsed.type, parsed.period);
return { count, history };
}
+4 -13
View File
@@ -1,28 +1,19 @@
import { atom } from "jotai";
import { unwrap } from "jotai/utils";
import type { HistoryBucket, TimePeriod } from "@/lib/services/discovery";
import { getStatsAction } from "@/lib/actions/watchlist";
import type { TimePeriod } from "@/lib/services/discovery";
export const moviePeriodAtom = atom<TimePeriod>("this_month");
export const episodePeriodAtom = atom<TimePeriod>("this_week");
async function fetchStats(
type: "movies" | "episodes",
period: TimePeriod,
): Promise<{ count: number; history: HistoryBucket[] }> {
const res = await fetch(
`/api/stats?type=${type}&period=${period}&history=true`,
);
return res.json();
}
const movieStatsAsyncAtom = atom(async (get) => {
const period = get(moviePeriodAtom);
return fetchStats("movies", period);
return getStatsAction("movies", period);
});
const episodeStatsAsyncAtom = atom(async (get) => {
const period = get(episodePeriodAtom);
return fetchStats("episodes", period);
return getStatsAction("episodes", period);
});
export const movieStatsAtom = unwrap(movieStatsAsyncAtom);
+7
View File
@@ -0,0 +1,7 @@
import { atom } from "jotai";
import type { SystemHealthData } from "@/lib/services/system-health";
export const systemHealthDataAtom = atom<SystemHealthData>(
undefined as unknown as SystemHealthData,
);
export const systemHealthRefreshingAtom = atom(false);