refactor: Amélioration de la page d'accueil et du cache - Suppression du cache.service.ts redondant - Mise à jour de l'ordre des sections (ongoing, onDeck, recentlyRead) - Correction des types et interfaces
This commit is contained in:
51
devbook.md
51
devbook.md
@@ -1,8 +1,8 @@
|
||||
# Plan de développement - Paniels (Komga Reader)
|
||||
# 📚 Paniels - Devbook
|
||||
|
||||
## 🎯 Objectif
|
||||
## 🎯 Objectifs
|
||||
|
||||
Créer une application web moderne avec Next.js permettant de lire des fichiers CBZ, CBR, EPUB et PDF via un serveur Komga.
|
||||
Application web moderne pour la lecture de BD/mangas/comics via un serveur Komga.
|
||||
|
||||
## 📋 Fonctionnalités principales
|
||||
|
||||
@@ -169,20 +169,39 @@ Créer une application web moderne avec Next.js permettant de lire des fichiers
|
||||
- [x] Service d'API
|
||||
- [x] Client HTTP avec fetch natif
|
||||
- [x] Gestion des tokens Basic Auth
|
||||
- [x] Cache des réponses
|
||||
- [x] Cache en mémoire côté serveur
|
||||
- [x] TTL configurable (5 minutes par défaut)
|
||||
- [x] Cache par route et paramètres
|
||||
- [x] Endpoints
|
||||
- [x] Authentication
|
||||
- [x] Bibliothèques
|
||||
- [x] Cache des requêtes
|
||||
- [x] Gestion des erreurs
|
||||
- [x] Typage des réponses
|
||||
- [x] Endpoints
|
||||
- [x] Authentification
|
||||
- [x] Collections
|
||||
- [x] Séries
|
||||
- [x] Livres
|
||||
- [x] Pages
|
||||
- [x] Gestion des erreurs
|
||||
- [x] Retry automatique
|
||||
- [x] Feedback utilisateur
|
||||
- [x] Messages d'erreur détaillés
|
||||
- [x] Tomes
|
||||
- [x] Progression de lecture
|
||||
- [x] Images et miniatures
|
||||
|
||||
## 🚀 Prochaines étapes
|
||||
|
||||
- [ ] Amélioration de l'UX
|
||||
- [ ] Animations de transition
|
||||
- [ ] Retour haptique
|
||||
- [ ] Messages de confirmation
|
||||
- [ ] Tooltips d'aide
|
||||
- [ ] Fonctionnalités avancées
|
||||
- [ ] Recherche globale
|
||||
- [ ] Filtres avancés
|
||||
- [ ] Tri personnalisé
|
||||
- [ ] Vue liste/grille configurable
|
||||
- [ ] Performance
|
||||
- [ ] Optimisation des images
|
||||
- [ ] Lazy loading amélioré
|
||||
- [ ] Prefetching intelligent
|
||||
- [ ] Cache optimisé
|
||||
- [ ] Accessibilité
|
||||
- [ ] Navigation au clavier
|
||||
- [ ] Support lecteur d'écran
|
||||
- [ ] Contraste et lisibilité
|
||||
- [ ] ARIA labels
|
||||
|
||||
## 🎨 UI/UX
|
||||
|
||||
|
||||
15
src/app/api/komga/cache/clear/route.ts
vendored
Normal file
15
src/app/api/komga/cache/clear/route.ts
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { serverCacheService } from "@/lib/services/server-cache.service";
|
||||
|
||||
export async function POST() {
|
||||
try {
|
||||
serverCacheService.clear();
|
||||
return NextResponse.json({ message: "Cache serveur supprimé avec succès" });
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la suppression du cache serveur:", error);
|
||||
return NextResponse.json(
|
||||
{ error: "Erreur lors de la suppression du cache serveur" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,11 @@ export async function POST(request: Request) {
|
||||
credentials: { username, password },
|
||||
};
|
||||
|
||||
const result = await TestService.testConnection(config);
|
||||
return NextResponse.json(result);
|
||||
const { libraries } = await TestService.testConnection(config);
|
||||
return NextResponse.json({
|
||||
message: "Connexion réussie",
|
||||
librariesCount: libraries.length,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Erreur lors du test de connexion:", error);
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -6,9 +6,9 @@ import { useRouter } from "next/navigation";
|
||||
import { KomgaBook, KomgaSeries } from "@/types/komga";
|
||||
|
||||
interface HomeData {
|
||||
onGoingSeries: KomgaSeries[];
|
||||
ongoing: KomgaSeries[];
|
||||
recentlyRead: KomgaBook[];
|
||||
popularSeries: KomgaSeries[];
|
||||
onDeck: KomgaBook[];
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
@@ -29,9 +29,9 @@ export default function HomePage() {
|
||||
const jsonData = await response.json();
|
||||
// Transformer les données pour correspondre à l'interface HomeData
|
||||
setData({
|
||||
onGoingSeries: jsonData.ongoing || [],
|
||||
ongoing: jsonData.ongoing || [],
|
||||
recentlyRead: jsonData.recentlyRead || [],
|
||||
popularSeries: jsonData.popular || [],
|
||||
onDeck: jsonData.onDeck || [],
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la récupération des données:", error);
|
||||
@@ -75,6 +75,7 @@ export default function HomePage() {
|
||||
}
|
||||
|
||||
if (!data) return null;
|
||||
console.log("PAGE", data);
|
||||
|
||||
return <HomeContent data={data} />;
|
||||
}
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Loader2, Network, Trash2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { storageService } from "@/lib/services/storage.service";
|
||||
import { AuthError } from "@/types/auth";
|
||||
|
||||
interface ErrorMessage {
|
||||
message: string;
|
||||
}
|
||||
|
||||
export default function SettingsPage() {
|
||||
const router = useRouter();
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isCacheClearing, setIsCacheClearing] = useState(false);
|
||||
const [error, setError] = useState<AuthError | null>(null);
|
||||
const [success, setSuccess] = useState(false);
|
||||
const [success, setSuccess] = useState<string | null>(null);
|
||||
const [config, setConfig] = useState({
|
||||
serverUrl: "",
|
||||
username: "",
|
||||
@@ -29,17 +35,38 @@ export default function SettingsPage() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleTest = async () => {
|
||||
if (!formRef.current) return;
|
||||
const handleClearCache = async () => {
|
||||
setIsCacheClearing(true);
|
||||
setError(null);
|
||||
setSuccess(null);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/komga/cache/clear", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(data.error || "Erreur lors de la suppression du cache");
|
||||
}
|
||||
|
||||
setSuccess("Cache serveur supprimé avec succès");
|
||||
router.refresh(); // Rafraîchir la page pour recharger les données
|
||||
} catch (error) {
|
||||
console.error("Erreur:", error);
|
||||
setError({
|
||||
code: "CACHE_CLEAR_ERROR",
|
||||
message: error instanceof Error ? error.message : "Une erreur est survenue",
|
||||
});
|
||||
} finally {
|
||||
setIsCacheClearing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTest = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
setSuccess(false);
|
||||
|
||||
const formData = new FormData(formRef.current);
|
||||
const serverUrl = formData.get("serverUrl") as string;
|
||||
const username = formData.get("username") as string;
|
||||
const password = formData.get("password") as string;
|
||||
setSuccess(null);
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/komga/test", {
|
||||
@@ -48,28 +75,23 @@ export default function SettingsPage() {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
serverUrl: serverUrl.trim(),
|
||||
username,
|
||||
password,
|
||||
serverUrl: config.serverUrl,
|
||||
username: config.username,
|
||||
password: config.password,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const data = await response.json();
|
||||
throw new Error(
|
||||
`${data.error}${
|
||||
data.details ? `\n\nDétails: ${JSON.stringify(data.details, null, 2)}` : ""
|
||||
}`
|
||||
);
|
||||
throw new Error(data.error || "Erreur lors du test de connexion");
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
setSuccess("Connexion réussie");
|
||||
} catch (error) {
|
||||
console.error("Erreur de test:", error);
|
||||
console.error("Erreur:", error);
|
||||
setError({
|
||||
code: "INVALID_SERVER_URL",
|
||||
message:
|
||||
error instanceof Error ? error.message : "Impossible de se connecter au serveur Komga",
|
||||
code: "TEST_CONNECTION_ERROR",
|
||||
message: error instanceof Error ? error.message : "Une erreur est survenue",
|
||||
});
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
@@ -78,7 +100,7 @@ export default function SettingsPage() {
|
||||
|
||||
const handleSave = (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setSuccess(false);
|
||||
setSuccess(null);
|
||||
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const serverUrl = formData.get("serverUrl") as string;
|
||||
@@ -100,120 +122,151 @@ export default function SettingsPage() {
|
||||
);
|
||||
|
||||
setConfig(newConfig);
|
||||
setSuccess(true);
|
||||
setSuccess("Configuration sauvegardée avec succès");
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="container max-w-2xl">
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<div className="container py-8 space-y-8">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-3xl font-bold">Préférences</h1>
|
||||
<p className="text-muted-foreground mt-2">Configurez votre connexion au serveur Komga</p>
|
||||
</div>
|
||||
|
||||
<div className="rounded-lg border bg-card text-card-foreground shadow-sm p-6">
|
||||
<h2 className="text-xl font-semibold mb-4">Configuration du serveur Komga</h2>
|
||||
<p className="text-sm text-muted-foreground mb-6">
|
||||
Ces identifiants sont différents de ceux utilisés pour vous connecter à l'application.
|
||||
Il s'agit des identifiants de votre serveur Komga.
|
||||
</p>
|
||||
|
||||
<form ref={formRef} className="space-y-8" onSubmit={handleSave}>
|
||||
<div className="space-y-6">
|
||||
{/* Section Configuration Komga */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h2 className="text-xl font-semibold">Configuration Komga</h2>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Configurez les informations de connexion à votre serveur Komga. Ces informations sont
|
||||
nécessaires pour accéder à votre bibliothèque.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
{/* Formulaire de configuration */}
|
||||
<div className="space-y-4">
|
||||
<form ref={formRef} onSubmit={handleSave} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="serverUrl"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
URL du serveur Komga
|
||||
<label htmlFor="serverUrl" className="text-sm font-medium">
|
||||
URL du serveur
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
L'adresse de votre serveur Komga, par exemple : https://komga.votredomaine.com
|
||||
</p>
|
||||
<input
|
||||
type="url"
|
||||
id="serverUrl"
|
||||
name="serverUrl"
|
||||
type="url"
|
||||
placeholder="https://komga.example.com"
|
||||
defaultValue={config.serverUrl || process.env.NEXT_PUBLIC_DEFAULT_KOMGA_URL}
|
||||
required
|
||||
defaultValue={config.serverUrl}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
L'URL complète de votre serveur Komga, par exemple: https://komga.example.com
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="username"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
Identifiant Komga
|
||||
<label htmlFor="username" className="text-sm font-medium">
|
||||
Nom d'utilisateur
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Votre identifiant de connexion au serveur Komga
|
||||
</p>
|
||||
<input
|
||||
type="text"
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
defaultValue={config.username}
|
||||
required
|
||||
defaultValue={config.username}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
L'identifiant de votre compte sur le serveur Komga
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
Mot de passe Komga
|
||||
<label htmlFor="password" className="text-sm font-medium">
|
||||
Mot de passe
|
||||
</label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Votre mot de passe de connexion au serveur Komga
|
||||
</p>
|
||||
<input
|
||||
type="password"
|
||||
id="password"
|
||||
name="password"
|
||||
type="password"
|
||||
defaultValue={config.password}
|
||||
required
|
||||
defaultValue={config.password}
|
||||
className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
/>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Le mot de passe de votre compte sur le serveur Komga
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/15 p-3 text-sm text-destructive">
|
||||
{error.message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{success && (
|
||||
<div className="rounded-md bg-green-500/15 p-3 text-sm text-green-500">
|
||||
{isLoading ? "Test de connexion réussi" : "Configuration sauvegardée"}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex space-x-4">
|
||||
<button
|
||||
type="button"
|
||||
disabled={isLoading}
|
||||
onClick={handleTest}
|
||||
className="flex-1 inline-flex items-center justify-center rounded-md border border-input bg-background px-4 py-2 text-sm font-medium ring-offset-background transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? "Test en cours..." : "Tester la connexion"}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="flex-1 inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
|
||||
className="w-full inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground ring-offset-background transition-colors hover:bg-primary/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
Sauvegarder
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<h3 className="text-sm font-medium">Actions</h3>
|
||||
<p className="text-xs text-muted-foreground mb-4">
|
||||
Outils de gestion de la connexion et du cache
|
||||
</p>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<button
|
||||
onClick={handleTest}
|
||||
disabled={isLoading}
|
||||
className="w-full inline-flex items-center justify-center rounded-md bg-secondary px-4 py-2 text-sm font-medium text-secondary-foreground ring-offset-background transition-colors hover:bg-secondary/80 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Test en cours...
|
||||
</>
|
||||
) : (
|
||||
"Tester la connexion"
|
||||
)}
|
||||
</button>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Vérifie que la connexion au serveur est fonctionnelle avec les paramètres
|
||||
actuels
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<button
|
||||
onClick={handleClearCache}
|
||||
disabled={isCacheClearing}
|
||||
className="w-full inline-flex items-center justify-center rounded-md bg-destructive px-4 py-2 text-sm font-medium text-destructive-foreground ring-offset-background transition-colors hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50"
|
||||
>
|
||||
{isCacheClearing ? (
|
||||
<>
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
Suppression...
|
||||
</>
|
||||
) : (
|
||||
"Supprimer le cache serveur"
|
||||
)}
|
||||
</button>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
Vide le cache du serveur pour forcer le rechargement des données. Utile en cas
|
||||
de problème d'affichage.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Messages de succès/erreur */}
|
||||
{error && (
|
||||
<div className="rounded-md bg-destructive/15 p-4">
|
||||
<p className="text-sm text-destructive">{error.message}</p>
|
||||
</div>
|
||||
)}
|
||||
{success && (
|
||||
<div className="rounded-md bg-green-500/15 p-4">
|
||||
<p className="text-sm text-green-500">{success}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -7,15 +7,14 @@ import { useRouter } from "next/navigation";
|
||||
|
||||
interface HomeContentProps {
|
||||
data: {
|
||||
onGoingSeries: KomgaSeries[];
|
||||
ongoing: KomgaSeries[];
|
||||
recentlyRead: KomgaBook[];
|
||||
popularSeries: KomgaSeries[];
|
||||
onDeck: KomgaBook[];
|
||||
};
|
||||
}
|
||||
|
||||
export function HomeContent({ data }: HomeContentProps) {
|
||||
const router = useRouter();
|
||||
|
||||
const handleItemClick = (item: KomgaSeries | KomgaBook) => {
|
||||
// Si c'est une série (a la propriété booksCount), on va vers la page de la série
|
||||
if ("booksCount" in item) {
|
||||
@@ -28,28 +27,30 @@ export function HomeContent({ data }: HomeContentProps) {
|
||||
|
||||
// Vérification des données pour le debug
|
||||
console.log("HomeContent - Données reçues:", {
|
||||
onGoingCount: data.onGoingSeries?.length || 0,
|
||||
ongoingCount: data.ongoing?.length || 0,
|
||||
recentlyReadCount: data.recentlyRead?.length || 0,
|
||||
popularCount: data.popularSeries?.length || 0,
|
||||
onDeckCount: data.onDeck?.length || 0,
|
||||
});
|
||||
|
||||
return (
|
||||
<main className="container mx-auto px-4 py-8 space-y-12">
|
||||
{/* Hero Section - Afficher uniquement si nous avons des séries populaires */}
|
||||
{data.popularSeries && data.popularSeries.length > 0 && (
|
||||
<HeroSection series={data.popularSeries} />
|
||||
)}
|
||||
{/* Hero Section - Afficher uniquement si nous avons des séries en cours */}
|
||||
{data.ongoing && data.ongoing.length > 0 && <HeroSection series={data.ongoing} />}
|
||||
|
||||
{/* Sections de contenu */}
|
||||
<div className="space-y-12">
|
||||
{data.onGoingSeries && data.onGoingSeries.length > 0 && (
|
||||
{data.ongoing && data.ongoing.length > 0 && (
|
||||
<MediaRow
|
||||
title="Continuer la lecture"
|
||||
items={data.onGoingSeries}
|
||||
items={data.ongoing}
|
||||
onItemClick={handleItemClick}
|
||||
/>
|
||||
)}
|
||||
|
||||
{data.onDeck && data.onDeck.length > 0 && (
|
||||
<MediaRow title="À suivre" items={data.onDeck} onItemClick={handleItemClick} />
|
||||
)}
|
||||
|
||||
{data.recentlyRead && data.recentlyRead.length > 0 && (
|
||||
<MediaRow
|
||||
title="Dernières lectures"
|
||||
@@ -57,14 +58,6 @@ export function HomeContent({ data }: HomeContentProps) {
|
||||
onItemClick={handleItemClick}
|
||||
/>
|
||||
)}
|
||||
|
||||
{data.popularSeries && data.popularSeries.length > 0 && (
|
||||
<MediaRow
|
||||
title="Séries populaires"
|
||||
items={data.popularSeries}
|
||||
onItemClick={handleItemClick}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
class CacheService {
|
||||
private static instance: CacheService;
|
||||
private cacheName = "komga-cache-v1";
|
||||
|
||||
private static readonly fiveMinutes = 5 * 60;
|
||||
private static readonly tenMinutes = 10 * 60;
|
||||
private static readonly twentyFourHours = 24 * 60 * 60;
|
||||
private static readonly oneMinute = 1 * 60;
|
||||
private static readonly noCache = 0;
|
||||
|
||||
// Configuration des temps de cache en secondes
|
||||
private static readonly TTL = {
|
||||
DEFAULT: CacheService.fiveMinutes, // 5 minutes
|
||||
HOME: CacheService.fiveMinutes, // 5 minutes
|
||||
LIBRARIES: CacheService.tenMinutes, // 10 minutes
|
||||
SERIES: CacheService.fiveMinutes, // 5 minutes
|
||||
BOOKS: CacheService.fiveMinutes, // 5 minutes
|
||||
IMAGES: CacheService.twentyFourHours, // 24 heures
|
||||
READ_PROGRESS: CacheService.oneMinute, // 1 minute
|
||||
};
|
||||
// private static readonly TTL = {
|
||||
// DEFAULT: CacheService.noCache, // 5 minutes
|
||||
// HOME: CacheService.noCache, // 5 minutes
|
||||
// LIBRARIES: CacheService.noCache, // 10 minutes
|
||||
// SERIES: CacheService.noCache, // 5 minutes
|
||||
// BOOKS: CacheService.noCache, // 5 minutes
|
||||
// IMAGES: CacheService.noCache, // 24 heures
|
||||
// READ_PROGRESS: CacheService.noCache, // 1 minute
|
||||
// };
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): CacheService {
|
||||
if (!CacheService.instance) {
|
||||
CacheService.instance = new CacheService();
|
||||
}
|
||||
return CacheService.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retourne le TTL pour un type de données spécifique
|
||||
*/
|
||||
public getTTL(type: keyof typeof CacheService.TTL): number {
|
||||
return CacheService.TTL[type];
|
||||
}
|
||||
|
||||
/**
|
||||
* Met en cache une réponse avec une durée de vie
|
||||
*/
|
||||
async set(
|
||||
key: string,
|
||||
response: Response,
|
||||
ttl: number = CacheService.TTL.DEFAULT
|
||||
): Promise<void> {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
const cache = await caches.open(this.cacheName);
|
||||
const headers = new Headers(response.headers);
|
||||
headers.append("x-cache-timestamp", Date.now().toString());
|
||||
headers.append("x-cache-ttl", ttl.toString());
|
||||
|
||||
const cachedResponse = new Response(await response.clone().blob(), {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
headers,
|
||||
});
|
||||
|
||||
await cache.put(key, cachedResponse);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la mise en cache:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère une réponse du cache si elle est valide
|
||||
*/
|
||||
async get(key: string): Promise<Response | null> {
|
||||
if (typeof window === "undefined") return null;
|
||||
|
||||
try {
|
||||
const cache = await caches.open(this.cacheName);
|
||||
const response = await cache.match(key);
|
||||
|
||||
if (!response) return null;
|
||||
|
||||
// Vérifier si la réponse est expirée
|
||||
const timestamp = parseInt(response.headers.get("x-cache-timestamp") || "0");
|
||||
const ttl = parseInt(response.headers.get("x-cache-ttl") || "0");
|
||||
const now = Date.now();
|
||||
|
||||
if (now - timestamp > ttl * 1000) {
|
||||
await cache.delete(key);
|
||||
return null;
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la lecture du cache:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Supprime une entrée du cache
|
||||
*/
|
||||
async delete(key: string): Promise<void> {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
const cache = await caches.open(this.cacheName);
|
||||
await cache.delete(key);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors de la suppression du cache:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Vide le cache
|
||||
*/
|
||||
async clear(): Promise<void> {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
try {
|
||||
await caches.delete(this.cacheName);
|
||||
} catch (error) {
|
||||
console.error("Erreur lors du nettoyage du cache:", error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Récupère une réponse du cache ou fait l'appel API si nécessaire
|
||||
*/
|
||||
async getOrFetch(
|
||||
key: string,
|
||||
fetcher: () => Promise<Response>,
|
||||
type: keyof typeof CacheService.TTL = "DEFAULT"
|
||||
): Promise<Response> {
|
||||
const cachedResponse = await this.get(key);
|
||||
if (cachedResponse) {
|
||||
return cachedResponse;
|
||||
}
|
||||
|
||||
const response = await fetcher();
|
||||
const clonedResponse = response.clone();
|
||||
await this.set(key, clonedResponse, CacheService.TTL[type]);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
export const cacheService = CacheService.getInstance();
|
||||
@@ -5,7 +5,7 @@ import { LibraryResponse } from "@/types/library";
|
||||
interface HomeData {
|
||||
ongoing: KomgaSeries[];
|
||||
recentlyRead: KomgaBook[];
|
||||
popular: KomgaSeries[];
|
||||
onDeck: KomgaBook[];
|
||||
}
|
||||
|
||||
export class HomeService extends BaseApiService {
|
||||
@@ -34,27 +34,25 @@ export class HomeService extends BaseApiService {
|
||||
media_status: "READY",
|
||||
});
|
||||
|
||||
const popularUrl = this.buildUrl(config, "series", {
|
||||
const onDeckUrl = this.buildUrl(config, "books/ondeck", {
|
||||
page: "0",
|
||||
size: "20",
|
||||
sort: "metadata.titleSort,asc",
|
||||
media_status: "READY",
|
||||
});
|
||||
|
||||
// Appels API parallèles avec fetchFromApi
|
||||
const [ongoing, recentlyRead, popular] = await Promise.all([
|
||||
const [ongoing, recentlyRead, onDeck] = await Promise.all([
|
||||
this.fetchFromApi<LibraryResponse<KomgaSeries>>(ongoingUrl, headers),
|
||||
this.fetchFromApi<LibraryResponse<KomgaBook>>(recentlyReadUrl, headers),
|
||||
this.fetchFromApi<LibraryResponse<KomgaSeries>>(popularUrl, headers),
|
||||
this.fetchFromApi<LibraryResponse<KomgaBook>>(onDeckUrl, headers),
|
||||
]);
|
||||
|
||||
return {
|
||||
ongoing: ongoing.content || [],
|
||||
recentlyRead: recentlyRead.content || [],
|
||||
popular: popular.content || [],
|
||||
onDeck: onDeck.content || [],
|
||||
};
|
||||
},
|
||||
"HOME" // Type de cache
|
||||
"HOME"
|
||||
);
|
||||
} catch (error) {
|
||||
return this.handleError(error, "Impossible de récupérer les données de la page d'accueil");
|
||||
|
||||
@@ -8,15 +8,21 @@ class ServerCacheService {
|
||||
private static instance: ServerCacheService;
|
||||
private cache: Map<string, { data: unknown; expiry: number }> = new Map();
|
||||
|
||||
// Configuration des temps de cache en secondes (identique à CacheService)
|
||||
private static readonly fiveMinutes = 5 * 60;
|
||||
private static readonly tenMinutes = 10 * 60;
|
||||
private static readonly twentyFourHours = 24 * 60 * 60;
|
||||
private static readonly oneMinute = 1 * 60;
|
||||
private static readonly noCache = 0;
|
||||
|
||||
// Configuration des temps de cache en secondes
|
||||
private static readonly TTL = {
|
||||
DEFAULT: 5 * 60, // 5 minutes
|
||||
HOME: 5 * 60, // 5 minutes
|
||||
LIBRARIES: 10 * 60, // 10 minutes
|
||||
SERIES: 5 * 60, // 5 minutes
|
||||
BOOKS: 5 * 60, // 5 minutes
|
||||
IMAGES: 24 * 60 * 60, // 24 heures
|
||||
READ_PROGRESS: 1 * 60, // 1 minute
|
||||
DEFAULT: ServerCacheService.fiveMinutes, // 5 minutes
|
||||
HOME: ServerCacheService.oneMinute, // 1 minute
|
||||
LIBRARIES: ServerCacheService.tenMinutes, // 10 minutes
|
||||
SERIES: ServerCacheService.fiveMinutes, // 5 minutes
|
||||
BOOKS: ServerCacheService.fiveMinutes, // 5 minutes
|
||||
IMAGES: ServerCacheService.twentyFourHours, // 24 heures
|
||||
READ_PROGRESS: ServerCacheService.oneMinute, // 1 minute
|
||||
};
|
||||
|
||||
private constructor() {
|
||||
@@ -89,6 +95,7 @@ class ServerCacheService {
|
||||
const cached = this.cache.get(key);
|
||||
|
||||
if (cached && cached.expiry > now) {
|
||||
console.log("Cache hit for key:", key);
|
||||
return cached.data as T;
|
||||
}
|
||||
|
||||
|
||||
30
src/lib/services/test.service.ts
Normal file
30
src/lib/services/test.service.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { BaseApiService } from "./base-api.service";
|
||||
import { AuthConfig } from "@/types/auth";
|
||||
import { KomgaLibrary } from "@/types/komga";
|
||||
|
||||
export class TestService extends BaseApiService {
|
||||
static async testConnection(config: AuthConfig): Promise<{ libraries: KomgaLibrary[] }> {
|
||||
try {
|
||||
const url = this.buildUrl(config, "libraries");
|
||||
const headers = this.getAuthHeaders(config);
|
||||
|
||||
const response = await fetch(url, { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.message || "Erreur lors du test de connexion");
|
||||
}
|
||||
|
||||
const libraries = await response.json();
|
||||
return { libraries };
|
||||
} catch (error) {
|
||||
console.error("Erreur lors du test de connexion:", error);
|
||||
if (error instanceof Error && error.message.includes("fetch")) {
|
||||
throw new Error(
|
||||
"Impossible de se connecter au serveur. Vérifiez l'URL et que le serveur est accessible."
|
||||
);
|
||||
}
|
||||
throw error instanceof Error ? error : new Error("Erreur lors du test de connexion");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,4 +24,6 @@ export type AuthErrorCode =
|
||||
| "INVALID_SERVER_URL"
|
||||
| "SERVER_UNREACHABLE"
|
||||
| "NETWORK_ERROR"
|
||||
| "UNKNOWN_ERROR";
|
||||
| "UNKNOWN_ERROR"
|
||||
| "CACHE_CLEAR_ERROR"
|
||||
| "TEST_CONNECTION_ERROR";
|
||||
|
||||
Reference in New Issue
Block a user