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 { cookies } from "next/headers";
|
||||||
import { PaginatedSeriesGrid } from "@/components/library/PaginatedSeriesGrid";
|
import { PaginatedSeriesGrid } from "@/components/library/PaginatedSeriesGrid";
|
||||||
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
||||||
|
import { LibraryService } from "@/lib/services/library.service";
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: { libraryId: string };
|
params: { libraryId: string };
|
||||||
@@ -13,30 +14,16 @@ async function getLibrarySeries(libraryId: string, page: number = 1, unreadOnly:
|
|||||||
try {
|
try {
|
||||||
const cookiesStore = cookies();
|
const cookiesStore = cookies();
|
||||||
const config = komgaConfigService.validateAndGetConfig(cookiesStore);
|
const config = komgaConfigService.validateAndGetConfig(cookiesStore);
|
||||||
|
const pageIndex = page - 1;
|
||||||
|
|
||||||
// Paramètres de pagination
|
const series = await LibraryService.getLibrarySeries(
|
||||||
const pageIndex = page - 1; // L'API Komga utilise un index base 0
|
libraryId,
|
||||||
|
pageIndex,
|
||||||
|
PAGE_SIZE,
|
||||||
|
unreadOnly
|
||||||
|
);
|
||||||
|
|
||||||
// Construire l'URL avec les paramètres
|
return { data: series, serverUrl: config.serverUrl };
|
||||||
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 };
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw error instanceof Error ? error : new Error("Erreur lors de la récupération des séries");
|
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 { HomeContent } from "@/components/home/HomeContent";
|
||||||
import { useState, useEffect } from "react";
|
import { HomeService } from "@/lib/services/home.service";
|
||||||
import { useRouter } from "next/navigation";
|
import { cookies } from "next/headers";
|
||||||
import { KomgaBook, KomgaSeries } from "@/types/komga";
|
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
||||||
import { useToast } from "@/components/ui/use-toast";
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
interface HomeData {
|
export default async function HomePage() {
|
||||||
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 () => {
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/komga/home");
|
const cookiesStore = cookies();
|
||||||
if (!response.ok) {
|
komgaConfigService.validateAndGetConfig(cookiesStore);
|
||||||
const errorData = await response.json();
|
|
||||||
throw new Error(errorData.error || `Erreur ${response.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const jsonData = await response.json();
|
const data = await HomeService.getHomeData();
|
||||||
setData({
|
|
||||||
ongoing: jsonData.ongoing || [],
|
return <HomeContent data={data} />;
|
||||||
recentlyRead: jsonData.recentlyRead || [],
|
|
||||||
onDeck: jsonData.onDeck || [],
|
|
||||||
});
|
|
||||||
} catch (error) {
|
} 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
|
// Si l'erreur indique une configuration manquante, rediriger vers les préférences
|
||||||
if (errorMessage.includes("Configuration Komga manquante")) {
|
if (error instanceof Error && error.message.includes("Configuration Komga manquante")) {
|
||||||
toast({
|
redirect("/settings");
|
||||||
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) {
|
|
||||||
return (
|
return (
|
||||||
<main className="container mx-auto px-4 py-8">
|
<main className="container mx-auto px-4 py-8">
|
||||||
<div className="rounded-md bg-destructive/15 p-4">
|
<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>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return data ? <HomeContent data={data} /> : null;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { PaginatedBookGrid } from "@/components/series/PaginatedBookGrid";
|
import { PaginatedBookGrid } from "@/components/series/PaginatedBookGrid";
|
||||||
import { SeriesHeader } from "@/components/series/SeriesHeader";
|
import { SeriesHeader } from "@/components/series/SeriesHeader";
|
||||||
import { KomgaSeries, KomgaBook } from "@/types/komga";
|
|
||||||
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
import { komgaConfigService } from "@/lib/services/komga-config.service";
|
||||||
|
import { SeriesService } from "@/lib/services/series.service";
|
||||||
|
import { KomgaSeries } from "@/types/komga";
|
||||||
|
|
||||||
interface PageProps {
|
interface PageProps {
|
||||||
params: { seriesId: string };
|
params: { seriesId: string };
|
||||||
@@ -18,40 +19,14 @@ export default async function SeriesPage({ params, searchParams }: PageProps) {
|
|||||||
try {
|
try {
|
||||||
const cookiesStore = cookies();
|
const cookiesStore = cookies();
|
||||||
const config = komgaConfigService.validateAndGetConfig(cookiesStore);
|
const config = komgaConfigService.validateAndGetConfig(cookiesStore);
|
||||||
|
const pageIndex = currentPage - 1;
|
||||||
// Paramètres de pagination
|
|
||||||
const pageIndex = currentPage - 1; // L'API Komga utilise un index base 0
|
|
||||||
|
|
||||||
// Appels API parallèles pour les détails de la série et les tomes
|
// Appels API parallèles pour les détails de la série et les tomes
|
||||||
const [seriesResponse, booksResponse] = await Promise.all([
|
const [series, books] = await Promise.all([
|
||||||
// Détails de la série
|
SeriesService.getSeries(params.seriesId),
|
||||||
fetch(komgaConfigService.buildApiUrl(`series/${params.seriesId}`, cookiesStore), {
|
SeriesService.getSeriesBooks(params.seriesId, pageIndex, PAGE_SIZE, unreadOnly),
|
||||||
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 },
|
|
||||||
}
|
|
||||||
),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
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 (
|
return (
|
||||||
<div className="container py-8 space-y-8">
|
<div className="container py-8 space-y-8">
|
||||||
<SeriesHeader series={series} />
|
<SeriesHeader series={series} />
|
||||||
|
|||||||
@@ -146,6 +146,12 @@ export default function SettingsPage() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
komgaConfigService.setConfig(komgaConfig, true);
|
komgaConfigService.setConfig(komgaConfig, true);
|
||||||
|
|
||||||
|
fetch("/api/komga/config", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(komgaConfig),
|
||||||
|
});
|
||||||
|
|
||||||
setConfig(newConfig);
|
setConfig(newConfig);
|
||||||
|
|
||||||
// Émettre un événement pour notifier les autres composants
|
// Émettre un événement pour notifier les autres composants
|
||||||
|
|||||||
@@ -27,10 +27,11 @@ export class LibraryService extends BaseApiService {
|
|||||||
): Promise<LibraryResponse<Series>> {
|
): Promise<LibraryResponse<Series>> {
|
||||||
try {
|
try {
|
||||||
const config = await this.getKomgaConfig();
|
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(),
|
page: page.toString(),
|
||||||
size: size.toString(),
|
size: size.toString(),
|
||||||
...(unreadOnly && { read_status: "UNREAD" }),
|
...(unreadOnly && { read_status: "UNREAD,IN_PROGRESS" }),
|
||||||
});
|
});
|
||||||
const headers = this.getAuthHeaders(config);
|
const headers = this.getAuthHeaders(config);
|
||||||
|
|
||||||
|
|||||||
@@ -1,18 +1,17 @@
|
|||||||
import { BaseApiService } from "./base-api.service";
|
import { BaseApiService } from "./base-api.service";
|
||||||
import { Series } from "@/types/series";
|
|
||||||
import { LibraryResponse } from "@/types/library";
|
import { LibraryResponse } from "@/types/library";
|
||||||
import { KomgaBook } from "@/types/komga";
|
import { KomgaBook, KomgaSeries } from "@/types/komga";
|
||||||
|
|
||||||
export class SeriesService extends BaseApiService {
|
export class SeriesService extends BaseApiService {
|
||||||
static async getSeries(seriesId: string): Promise<Series> {
|
static async getSeries(seriesId: string): Promise<KomgaSeries> {
|
||||||
try {
|
try {
|
||||||
const config = await this.getKomgaConfig();
|
const config = await this.getKomgaConfig();
|
||||||
const url = this.buildUrl(config, `series/${seriesId}`);
|
const url = this.buildUrl(config, `series/${seriesId}`);
|
||||||
const headers = this.getAuthHeaders(config);
|
const headers = this.getAuthHeaders(config);
|
||||||
|
|
||||||
return this.fetchWithCache<Series>(
|
return this.fetchWithCache<KomgaSeries>(
|
||||||
`series-${seriesId}`,
|
`series-${seriesId}`,
|
||||||
async () => this.fetchFromApi<Series>(url, headers),
|
async () => this.fetchFromApi<KomgaSeries>(url, headers),
|
||||||
"SERIES"
|
"SERIES"
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
Reference in New Issue
Block a user