ptitlutins/app/stores/voyageStore.ts
2025-09-15 23:03:42 +02:00

102 lines
No EOL
2.8 KiB
TypeScript

import { defineStore } from 'pinia';
import { voyageService } from '../services/voyageService';
interface VoyageData {
title: string;
description: string;
}
interface Voyage {
id: string;
title: string;
description: string;
}
export const useVoyageStore = defineStore('voyage', {
state: () => ({
voyages: [] as Voyage[],
currentVoyage: null as Voyage | null,
isLoading: false,
error: null as string | null,
}),
actions: {
async fetchVoyages() {
this.isLoading = true;
this.error = null;
try {
const voyages = await voyageService.getVoyages();
this.voyages = voyages;
} catch (error) {
this.error = error.message || 'Failed to fetch voyages';
} finally {
this.isLoading = false;
}
},
async addVoyage(voyageData: VoyageData) {
this.isLoading = true;
this.error = null;
try {
const newVoyage = await voyageService.createVoyage(voyageData);
this.voyages.push(newVoyage);
this.currentVoyage = newVoyage;
} catch (error) {
this.error = error.message || 'Failed to create voyage';
} finally {
this.isLoading = false;
}
},
async setCurrentVoyage(voyageId: string) {
this.isLoading = true;
this.error = null;
try {
const voyage = await voyageService.getVoyageDetails(voyageId);
this.currentVoyage = voyage;
} catch (error) {
this.error = error.message || 'Failed to fetch voyage details';
} finally {
this.isLoading = false;
}
},
clearCurrentVoyage() {
this.currentVoyage = null;
},
async updateVoyage(voyageId: string, voyageData: VoyageData) {
this.isLoading = true;
this.error = null;
try {
const updatedVoyage = await voyageService.updateVoyage(voyageId, voyageData);
const index = this.voyages.findIndex(v => v.id === voyageId);
if (index !== -1) {
this.voyages[index] = updatedVoyage;
}
if (this.currentVoyage && this.currentVoyage.id === voyageId) {
this.currentVoyage = updatedVoyage;
}
} catch (error) {
this.error = error.message || 'Failed to update voyage';
} finally {
this.isLoading = false;
}
},
async deleteVoyage(voyageId: string) {
this.isLoading = true;
this.error = null;
try {
await voyageService.deleteVoyage(voyageId);
this.voyages = this.voyages.filter(v => v.id !== voyageId);
if (this.currentVoyage && this.currentVoyage.id === voyageId) {
this.clearCurrentVoyage();
}
} catch (error) {
this.error = error.message || 'Failed to delete voyage';
} finally {
this.isLoading = false;
}
},
},
});