68 lines
2.0 KiB
JavaScript
68 lines
2.0 KiB
JavaScript
import {defineStore} from 'pinia'
|
|
import {apolloWrapper} from "src/graphql/apollo"
|
|
import {FLIGHT_DETAIL, FLIGHTS_LIST} from "src/graphql/queries/flights";
|
|
import {EDIT_FLIGHT, CREATE_FLIGHT, DELETE_FLIGHT} from "src/graphql/mutations/flight";
|
|
import {updateInItems} from "stores/helpers";
|
|
|
|
export const useFlightsStore = defineStore('Flights', {
|
|
state: () => ({
|
|
items: [],
|
|
isMutationRunning: false
|
|
}),
|
|
|
|
getters: {
|
|
getDetail: (state) => (flightId) => {
|
|
return state.items.find(f => f.id === flightId);
|
|
},
|
|
},
|
|
|
|
actions: {
|
|
create(formData) {
|
|
delete formData['id'];
|
|
return apolloWrapper.mutate(CREATE_FLIGHT, {input: formData}).then(({data}) => {
|
|
const flightId = data.createFlight.id;
|
|
|
|
// pitomy ohack kvuli tomu, ze se mi nedari dostat z API rovnou informace o nove vytvorenem letadle
|
|
this.fetchDetail(flightId).then(flight => {
|
|
this.items.push(flight);
|
|
})
|
|
|
|
return data.createFlight;
|
|
})
|
|
},
|
|
update(id, formData) {
|
|
this.isMutationRunning = true;
|
|
return apolloWrapper.mutate(EDIT_FLIGHT, {id: id, input: formData}).then(({data}) => {
|
|
const flight = data.editFlight;
|
|
updateInItems(this.items, "id", flight);
|
|
|
|
return flight;
|
|
}).finally(() => this.isMutationRunning = false);
|
|
},
|
|
fetchDetail(id, username = null) {
|
|
if (typeof id !== "number") {
|
|
id = parseInt(id);
|
|
}
|
|
return apolloWrapper.query(FLIGHT_DETAIL, {id, username}).then(result => result.data.flight);
|
|
},
|
|
fetch(username = null) {
|
|
return apolloWrapper
|
|
.query(FLIGHTS_LIST, {username})
|
|
.then((resp) => {
|
|
const data = resp.data;
|
|
this.items = data.flights;
|
|
return data.flights;
|
|
}).catch(err => console.log(err));
|
|
},
|
|
delete(id) {
|
|
return apolloWrapper.mutate(DELETE_FLIGHT, {id}).then(({data}) => {
|
|
|
|
const idx = this.items.indexOf(this.items.find(f => f.id === id));
|
|
this.items.splice(idx, 1);
|
|
|
|
return data.deleteFlight;
|
|
})
|
|
},
|
|
},
|
|
});
|