refacto: servercomponent and first route for config
This commit is contained in:
16
src/app/api/komga/config/route.ts
Normal file
16
src/app/api/komga/config/route.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const data = await request.json();
|
||||
console.log("Configuration Komga reçue:", data);
|
||||
|
||||
return NextResponse.json({ message: "Configuration reçue avec succès" }, { status: 200 });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la réception de la configuration:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la réception de la configuration" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { PaginatedSeriesGrid } from "@/components/library/PaginatedSeriesGrid";
|
||||
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
||||
import { LibraryService } from "@/lib/services/library.service";
|
||||
|
||||
interface PageProps {
|
||||
params: { libraryId: string };
|
||||
@@ -13,30 +14,16 @@ async function getLibrarySeries(libraryId: string, page: number = 1, unreadOnly:
|
||||
try {
|
||||
const cookiesStore = cookies();
|
||||
const config = komgaConfigService.validateAndGetConfig(cookiesStore);
|
||||
const pageIndex = page - 1;
|
||||
|
||||
// Paramètres de pagination
|
||||
const pageIndex = page - 1; // L'API Komga utilise un index base 0
|
||||
const series = await LibraryService.getLibrarySeries(
|
||||
libraryId,
|
||||
pageIndex,
|
||||
PAGE_SIZE,
|
||||
unreadOnly
|
||||
);
|
||||
|
||||
// Construire l'URL avec les paramètres
|
||||
let path = `series?library_id=${libraryId}&page=${pageIndex}&size=${PAGE_SIZE}`;
|
||||
if (unreadOnly) {
|
||||
path += "&read_status=UNREAD&read_status=IN_PROGRESS";
|
||||
}
|
||||
|
||||
const url = komgaConfigService.buildApiUrl(path, cookiesStore);
|
||||
const headers = komgaConfigService.getAuthHeaders(cookiesStore);
|
||||
|
||||
const response = await fetch(url, {
|
||||
headers,
|
||||
next: { revalidate: 300 }, // Cache de 5 minutes
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Erreur HTTP: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return { data, serverUrl: config.serverUrl };
|
||||
return { data: series, serverUrl: config.serverUrl };
|
||||
} catch (error) {
|
||||
throw error instanceof Error ? error : new Error("Erreur lors de la récupération des séries");
|
||||
}
|
||||
|
||||
@@ -1,90 +1,31 @@
|
||||
"use client";
|
||||
|
||||
import { HomeContent } from "@/components/home/HomeContent";
|
||||
import { useState, useEffect } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { KomgaBook, KomgaSeries } from "@/types/komga";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { HomeService } from "@/lib/services/home.service";
|
||||
import { cookies } from "next/headers";
|
||||
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
interface HomeData {
|
||||
ongoing: KomgaSeries[];
|
||||
recentlyRead: KomgaBook[];
|
||||
onDeck: KomgaBook[];
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const router = useRouter();
|
||||
const { toast } = useToast();
|
||||
const [data, setData] = useState<HomeData | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchHomeData = async () => {
|
||||
export default async function HomePage() {
|
||||
try {
|
||||
const response = await fetch("/api/komga/home");
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || `Erreur ${response.status}`);
|
||||
}
|
||||
const cookiesStore = cookies();
|
||||
komgaConfigService.validateAndGetConfig(cookiesStore);
|
||||
|
||||
const jsonData = await response.json();
|
||||
setData({
|
||||
ongoing: jsonData.ongoing || [],
|
||||
recentlyRead: jsonData.recentlyRead || [],
|
||||
onDeck: jsonData.onDeck || [],
|
||||
});
|
||||
const data = await HomeService.getHomeData();
|
||||
|
||||
return <HomeContent data={data} />;
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération des données:", error);
|
||||
const errorMessage = error instanceof Error ? error.message : "Une erreur est survenue";
|
||||
setError(errorMessage);
|
||||
|
||||
// Si l'erreur indique une configuration manquante, rediriger vers les préférences
|
||||
if (errorMessage.includes("Configuration Komga manquante")) {
|
||||
toast({
|
||||
title: "Configuration requise",
|
||||
description: "Veuillez configurer votre serveur Komga pour continuer",
|
||||
variant: "destructive",
|
||||
});
|
||||
router.push("/settings");
|
||||
}
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchHomeData();
|
||||
}, [router, toast]);
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<main className="container mx-auto px-4 py-8 space-y-12">
|
||||
<div className="h-[500px] -mx-4 sm:-mx-8 lg:-mx-14 bg-muted animate-pulse" />
|
||||
<div className="space-y-12">
|
||||
{[...Array(3)].map((_, i) => (
|
||||
<div key={i} className="space-y-4">
|
||||
<div className="h-8 w-48 bg-muted rounded animate-pulse" />
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
|
||||
{[...Array(6)].map((_, j) => (
|
||||
<div key={j} className="aspect-[2/3] bg-muted rounded animate-pulse" />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
if (error instanceof Error && error.message.includes("Configuration Komga manquante")) {
|
||||
redirect("/settings");
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<main className="container mx-auto px-4 py-8">
|
||||
<div className="rounded-md bg-destructive/15 p-4">
|
||||
<p className="text-sm text-destructive">{error}</p>
|
||||
<p className="text-sm text-destructive">
|
||||
{error instanceof Error ? error.message : "Une erreur est survenue"}
|
||||
</p>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return data ? <HomeContent data={data} /> : null;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { cookies } from "next/headers";
|
||||
import { PaginatedBookGrid } from "@/components/series/PaginatedBookGrid";
|
||||
import { SeriesHeader } from "@/components/series/SeriesHeader";
|
||||
import { KomgaSeries, KomgaBook } from "@/types/komga";
|
||||
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
||||
import { SeriesService } from "@/lib/services/series.service";
|
||||
import { KomgaSeries } from "@/types/komga";
|
||||
|
||||
interface PageProps {
|
||||
params: { seriesId: string };
|
||||
@@ -18,40 +19,14 @@ export default async function SeriesPage({ params, searchParams }: PageProps) {
|
||||
try {
|
||||
const cookiesStore = cookies();
|
||||
const config = komgaConfigService.validateAndGetConfig(cookiesStore);
|
||||
|
||||
// Paramètres de pagination
|
||||
const pageIndex = currentPage - 1; // L'API Komga utilise un index base 0
|
||||
const pageIndex = currentPage - 1;
|
||||
|
||||
// Appels API parallèles pour les détails de la série et les tomes
|
||||
const [seriesResponse, booksResponse] = await Promise.all([
|
||||
// Détails de la série
|
||||
fetch(komgaConfigService.buildApiUrl(`series/${params.seriesId}`, cookiesStore), {
|
||||
headers: komgaConfigService.getAuthHeaders(cookiesStore),
|
||||
next: { revalidate: 300 },
|
||||
}),
|
||||
// Liste des tomes avec pagination et filtre
|
||||
fetch(
|
||||
komgaConfigService.buildApiUrl(
|
||||
`series/${
|
||||
params.seriesId
|
||||
}/books?page=${pageIndex}&size=${PAGE_SIZE}&sort=metadata.numberSort,asc${
|
||||
unreadOnly ? "&read_status=UNREAD&read_status=IN_PROGRESS" : ""
|
||||
}`,
|
||||
cookiesStore
|
||||
),
|
||||
{
|
||||
headers: komgaConfigService.getAuthHeaders(cookiesStore),
|
||||
next: { revalidate: 300 },
|
||||
}
|
||||
),
|
||||
const [series, books] = await Promise.all([
|
||||
SeriesService.getSeries(params.seriesId),
|
||||
SeriesService.getSeriesBooks(params.seriesId, pageIndex, PAGE_SIZE, unreadOnly),
|
||||
]);
|
||||
|
||||
if (!seriesResponse.ok || !booksResponse.ok) {
|
||||
throw new Error("Erreur lors de la récupération des données");
|
||||
}
|
||||
|
||||
const [series, books] = await Promise.all([seriesResponse.json(), booksResponse.json()]);
|
||||
|
||||
return (
|
||||
<div className="container py-8 space-y-8">
|
||||
<SeriesHeader series={series} />
|
||||
|
||||
@@ -146,6 +146,12 @@ export default function SettingsPage() {
|
||||
};
|
||||
|
||||
komgaConfigService.setConfig(komgaConfig, true);
|
||||
|
||||
fetch("/api/komga/config", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(komgaConfig),
|
||||
});
|
||||
|
||||
setConfig(newConfig);
|
||||
|
||||
// Émettre un événement pour notifier les autres composants
|
||||
|
||||
@@ -27,10 +27,11 @@ export class LibraryService extends BaseApiService {
|
||||
): Promise<LibraryResponse<Series>> {
|
||||
try {
|
||||
const config = await this.getKomgaConfig();
|
||||
const url = this.buildUrl(config, `libraries/${libraryId}/series`, {
|
||||
const url = this.buildUrl(config, "series", {
|
||||
library_id: libraryId,
|
||||
page: page.toString(),
|
||||
size: size.toString(),
|
||||
...(unreadOnly && { read_status: "UNREAD" }),
|
||||
...(unreadOnly && { read_status: "UNREAD,IN_PROGRESS" }),
|
||||
});
|
||||
const headers = this.getAuthHeaders(config);
|
||||
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
import { BaseApiService } from "./base-api.service";
|
||||
import { Series } from "@/types/series";
|
||||
import { LibraryResponse } from "@/types/library";
|
||||
import { KomgaBook } from "@/types/komga";
|
||||
import { KomgaBook, KomgaSeries } from "@/types/komga";
|
||||
|
||||
export class SeriesService extends BaseApiService {
|
||||
static async getSeries(seriesId: string): Promise<Series> {
|
||||
static async getSeries(seriesId: string): Promise<KomgaSeries> {
|
||||
try {
|
||||
const config = await this.getKomgaConfig();
|
||||
const url = this.buildUrl(config, `series/${seriesId}`);
|
||||
const headers = this.getAuthHeaders(config);
|
||||
|
||||
return this.fetchWithCache<Series>(
|
||||
return this.fetchWithCache<KomgaSeries>(
|
||||
`series-${seriesId}`,
|
||||
async () => this.fetchFromApi<Series>(url, headers),
|
||||
async () => this.fetchFromApi<KomgaSeries>(url, headers),
|
||||
"SERIES"
|
||||
);
|
||||
} catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user