feat: intégration de @tanstack/vue-query pour la gestion des requêtes dans l'application Vue, ajout de nouveaux composables pour les chapitres et les détails des mangas, et mise à jour du store pour une meilleure gestion des états de chargement et d'erreur

This commit is contained in:
ext.jeremy.guillot@maxicoffee.domains
2025-03-30 16:58:05 +02:00
parent fd2d3cd640
commit 71242433e6
10 changed files with 355 additions and 169 deletions

View File

@@ -1,81 +1,82 @@
import {defineStore} from 'pinia';
import {ApiMangaRepository} from '../../infrastructure/api/apiMangaRepository';
import { defineStore } from 'pinia';
import { ApiMangaRepository } from '../../infrastructure/api/apiMangaRepository';
const mangaRepository = new ApiMangaRepository();
export const useMangaStore = defineStore('manga', {
state: () => ({
// État pour la collection
collection: null,
// État pour les détails
currentManga: null,
chapters: [],
loading: false,
error: null,
isBackgroundLoading: false
}),
actions: {
// Actions pour la collection
async loadCollection() {
if (this.loading) return;
this.loading = true;
this.error = null;
try {
this.collection = await mangaRepository.getCollection();
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
},
async refreshCollectionInBackground() {
if (this.isBackgroundLoading) return;
this.isBackgroundLoading = true;
try {
this.collection = await mangaRepository.getCollection();
} catch (err) {
console.error('Failed to refresh collection:', err);
} finally {
this.isBackgroundLoading = false;
}
},
// Actions pour les détails du manga
async fetchMangaDetails(mangaId) {
this.loading = true;
this.error = null;
try {
this.currentManga = await mangaRepository.getMangaById(mangaId);
} catch (error) {
this.error = error.message;
} finally {
this.loading = false;
}
},
async fetchMangaChapters(mangaId) {
this.loading = true;
this.error = null;
try {
const response = await mangaRepository.getChapters(mangaId);
this.chapters = Array.isArray(response) ? response :
(response.items ? response.items : []);
} catch (error) {
this.error = error.message;
} finally {
this.loading = false;
}
},
clearCurrentManga() {
this.currentManga = null;
this.chapters = [];
// Helper pour comparer la collection (peut être supprimé si non utilisé ailleurs)
const deepCompare = (obj1, obj2) => {
try {
if (obj1 == null && obj2 == null) return true;
if (obj1 == null || obj2 == null) return false;
return JSON.stringify(obj1) === JSON.stringify(obj2);
} catch (e) {
console.error("Erreur lors de la comparaison d'objets:", e);
return false;
}
};
export const useMangaStore = defineStore('manga', {
state: () => ({
// --- Collection State ---
collection: null,
loadingCollection: false,
errorCollection: null,
isBackgroundLoadingCollection: false,
// --- Selected Manga State ---
// Gardé pour savoir quel manga est sélectionné dans l'UI,
// mais les données détaillées ne sont plus stockées ici.
currentMangaId: null
}),
getters: {
// Plus de getters spécifiques aux détails/chapitres ici
},
actions: {
// --- Collection Actions ---
async loadCollection() {
if (this.loadingCollection) return;
this.loadingCollection = true;
this.errorCollection = null;
try {
const newCollection = await mangaRepository.getCollection();
// On garde la comparaison pour éviter màj inutile de la collection
if (!deepCompare(this.collection, newCollection)) {
this.collection = newCollection;
}
} catch (err) {
this.errorCollection = err.message;
} finally {
this.loadingCollection = false;
}
},
async refreshCollectionInBackground() {
if (this.isBackgroundLoadingCollection) return;
this.isBackgroundLoadingCollection = true;
try {
const newCollection = await mangaRepository.getCollection();
if (!deepCompare(this.collection, newCollection)) {
this.collection = newCollection;
}
} catch (err) {
console.error('Failed to refresh collection:', err);
} finally {
this.isBackgroundLoadingCollection = false;
}
},
// --- Selected Manga Actions ---
setCurrentMangaId(mangaId) {
// Met simplement à jour l'ID sélectionné
this.currentMangaId = mangaId;
},
clearCurrentMangaFocus() {
this.currentMangaId = null;
}
// Plus d'actions fetchMangaDetails / fetchMangaChapters ici
}
}
});

View File

@@ -0,0 +1,23 @@
import { computed } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { ApiMangaRepository } from '../../infrastructure/api/apiMangaRepository';
export function useMangaChapters(mangaId) {
const mangaRepository = new ApiMangaRepository();
const query = useQuery({
queryKey: ['manga', mangaId, 'chapters'],
queryFn: async () => {
if (!mangaId.value) {
return Promise.resolve([]); // Retourne un tableau vide si pas d'ID
}
const response = await mangaRepository.getChapters(mangaId.value);
// Assure de toujours retourner un tableau
return Array.isArray(response) ? response : response?.items ?? [];
},
enabled: computed(() => !!mangaId.value)
});
// Retourne le résultat de useQuery (contenant data, isLoading, etc.)
return query;
}

View File

@@ -0,0 +1,31 @@
import { computed } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { ApiMangaRepository } from '../../infrastructure/api/apiMangaRepository';
// Accepte un ID de manga (peut être une ref, un computed ref, ou une valeur simple)
export function useMangaDetails(mangaId) {
const mangaRepository = new ApiMangaRepository();
// Assure que mangaId est une ref ou une computed pour la réactivité de la queryKey
// Si ce n'est pas déjà le cas, mais généralement on passera une computed( () => route.params.id )
// const mangaIdRef = computed(() => unref(mangaId)); // unref est utile si on accepte des valeurs simples aussi
const query = useQuery({
// La queryKey doit être réactive à mangaId
queryKey: ['manga', mangaId], // mangaId est déjà une computed ref, donc c'est bon
queryFn: () => {
// Vérifier que l'ID a une valeur avant d'appeler l'API
if (!mangaId.value) {
// Retourner null ou undefined si pas d'ID, pour éviter un appel API invalide
// TanStack Query gère aussi l'option 'enabled' pour cela
return Promise.resolve(null); // ou throw new Error("ID manquant");
}
return mangaRepository.getMangaById(mangaId.value);
},
// Activer la requête seulement si mangaId a une valeur truthy
enabled: computed(() => !!mangaId.value)
});
// Retourne tous les états et données fournis par useQuery
return query;
}

View File

@@ -0,0 +1,51 @@
import { computed } from 'vue';
import { useMangaChapters } from './useMangaChapters'; // Importe le composable des chapitres
export function useMangaVolumes(mangaId) {
// Utilise le composable des chapitres pour récupérer les données brutes et les états
const { data: rawChaptersData, isLoading, isFetching, error, status } = useMangaChapters(mangaId);
// Calcule les volumes à partir des données des chapitres
const volumes = computed(() => {
const chaptersArray = rawChaptersData.value || []; // Utilise la data retournée par useMangaChapters
if (chaptersArray.length === 0) return [];
const volumeMap = new Map();
chaptersArray.forEach(chapter => {
const volumeNumber = chapter.volume || 'Unknown';
if (!volumeMap.has(volumeNumber)) {
volumeMap.set(volumeNumber, {
number: volumeNumber,
downloadedChapter: 0,
totalChapter: 0,
chapters: []
});
}
const volumeEntry = volumeMap.get(volumeNumber);
volumeEntry.chapters.push({
...chapter,
isAvailable: Boolean(chapter.isAvailable)
});
volumeEntry.totalChapter++;
if (chapter.isAvailable) {
volumeEntry.downloadedChapter++;
}
});
return Array.from(volumeMap.values()).sort((a, b) => {
const numA = a.number === 'Unknown' ? -Infinity : Number(a.number);
const numB = b.number === 'Unknown' ? -Infinity : Number(b.number);
return numB - numA;
});
});
// Retourne les volumes calculés et propage les états pertinents de useMangaChapters
return {
volumes, // Les données transformées
isLoading, // L'état de chargement initial des chapitres
isFetching, // L'état de rafraîchissement des chapitres
error, // L'erreur potentielle lors du fetch des chapitres
status // L'état global ('pending', 'error', 'success')
// On pourrait aussi retourner rawChaptersData si nécessaire ailleurs
};
}

View File

@@ -31,7 +31,12 @@
const router = useRouter();
const mangaStore = useMangaStore();
const { collection, loading, error, isBackgroundLoading } = storeToRefs(mangaStore);
const {
collection,
loadingCollection: loading,
errorCollection: error,
isBackgroundLoadingCollection: isBackgroundLoading
} = storeToRefs(mangaStore);
onMounted(() => {
mangaStore.loadCollection();

View File

@@ -3,84 +3,68 @@
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
</div>
<div v-else-if="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
{{ error }}
<div v-else-if="error && !currentManga" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
{{ error.message || 'Une erreur est survenue.' }}
</div>
<div v-else-if="currentManga" class="relative">
<div v-if="isRefreshing" class="absolute top-2 right-2 text-gray-500">
<ArrowPathIcon class="h-5 w-5 animate-spin" />
</div>
<MangaHeader :manga="currentManga" />
<MangaVolumeList :volumes="volumes" :manga-slug="currentManga.slug" />
</div>
<div v-else class="text-center text-gray-500 py-10"> Aucun manga sélectionné ou trouvé. </div>
</template>
<script setup>
import { computed, onMounted, onUnmounted, watch } from 'vue';
import { computed, onUnmounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { useMangaStore } from '../../application/store/mangaStore';
import { storeToRefs } from 'pinia';
import { ArrowPathIcon } from '@heroicons/vue/24/outline';
import { useMangaDetails } from '../composables/useMangaDetails';
import { useMangaVolumes } from '../composables/useMangaVolumes';
import MangaHeader from '../components/MangaHeader.vue';
import MangaVolumeList from '../components/MangaVolumeList.vue';
import { useMangaStore } from '../../application/store/mangaStore';
const route = useRoute();
const store = useMangaStore();
const { currentManga, chapters, loading, error } = storeToRefs(store);
const mangaStore = useMangaStore();
const volumes = computed(() => {
if (!chapters.value) return [];
const mangaId = computed(() => route.params.id || null);
const chaptersArray = Array.isArray(chapters.value)
? chapters.value
: chapters.value.items
? chapters.value.items
: [];
const {
data: currentManga,
isLoading: isLoadingDetails,
isFetching: isRefreshingDetails,
error: errorDetails
} = useMangaDetails(mangaId);
const volumeMap = new Map();
const {
volumes,
isLoading: isLoadingVolumes,
isFetching: isRefreshingVolumes,
error: errorVolumes
} = useMangaVolumes(mangaId);
chaptersArray.forEach(chapter => {
const volumeNumber = chapter.volume || 'Unknown';
if (!volumeMap.has(volumeNumber)) {
volumeMap.set(volumeNumber, {
number: volumeNumber,
downloadedChapter: 0,
totalChapter: 0,
chapters: []
});
}
const loading = computed(() => isLoadingDetails.value || isLoadingVolumes.value);
const isRefreshing = computed(() => isRefreshingDetails.value || isRefreshingVolumes.value);
const error = computed(() => errorDetails.value || errorVolumes.value);
volumeMap.get(volumeNumber).chapters.push({
...chapter,
isAvailable: Boolean(chapter.isAvailable)
});
});
for (const volume of volumeMap.values()) {
volume.downloadedChapter = volume.chapters.filter(c => c.isAvailable).length;
volume.totalChapter = volume.chapters.length;
}
return Array.from(volumeMap.values()).sort((a, b) => b.number - a.number);
});
const loadData = async () => {
const mangaId = route.params.id;
await Promise.all([store.fetchMangaDetails(mangaId), store.fetchMangaChapters(mangaId)]);
};
// Ajouter le watcher sur l'ID de la route
watch(
() => route.params.id,
(newId, oldId) => {
if (newId !== oldId) {
loadData();
mangaId,
newId => {
if (newId) {
mangaStore.setCurrentMangaId(newId);
}
}
},
{ immediate: true }
);
onMounted(() => {
loadData();
});
onUnmounted(() => {
store.clearCurrentManga();
mangaStore.clearCurrentMangaFocus();
});
</script>

View File

@@ -1,18 +1,18 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import { router } from './router'
import '../../styles/app.scss'
import { createApp } from 'vue';
import { createPinia } from 'pinia';
import App from './App.vue';
import { router } from './router';
import '../../styles/app.scss';
import { installVueQuery } from './shared/plugin/vueQuery';
// Création du store
const pinia = createPinia()
const pinia = createPinia();
// Création de l'application
const app = createApp(App)
const app = createApp(App);
// Installation des plugins
app.use(router)
app.use(pinia)
app.use(router);
app.use(pinia);
app.use(installVueQuery);
// Montage de l'application
app.mount('#vue-app')
app.mount('#vue-app');

View File

@@ -0,0 +1,25 @@
import { VueQueryPlugin, QueryClient } from '@tanstack/vue-query';
// Créez une instance de QueryClient
const queryClient = new QueryClient({
defaultOptions: {
queries: {
// Options par défaut pour toutes les requêtes (queries)
staleTime: 5 * 60 * 1000, // 5 minutes: temps pendant lequel les données sont considérées "fraîches" (ne déclenche pas de re-fetch en arrière-plan juste en montant le composant)
gcTime: 10 * 60 * 1000, // 10 minutes: temps avant que les données inactives soient supprimées du cache (garbage collected)
retry: 1, // Nombre de tentatives en cas d'erreur
refetchOnWindowFocus: true // Re-fetcher quand la fenêtre reprend le focus (bon pour garder les données à jour)
}
}
});
export const vueQueryPluginOptions = {
queryClient // Fournir le client au plugin
};
export const installVueQuery = app => {
app.use(VueQueryPlugin, vueQueryPluginOptions);
};
// Exportez aussi le client si vous avez besoin d'y accéder directement ailleurs (rare)
export { queryClient };