adrema/resources/js/composables/useApiIndex.js

96 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-10-13 13:07:16 +02:00
import {ref, inject, onBeforeUnmount} from 'vue';
import {router} from '@inertiajs/vue3';
import useQueueEvents from './useQueueEvents.js';
export function useApiIndex(url, siteName) {
const axios = inject('axios');
const {startListener, stopListener} = useQueueEvents(siteName, () => reload());
const single = ref(null);
const inner = {
data: ref([]),
meta: ref({}),
};
2024-04-26 23:20:03 +02:00
async function reload(resetPage = true, p = {}) {
2023-10-13 13:07:16 +02:00
var params = {
page: resetPage ? 1 : inner.meta.value.current_page,
2024-04-26 23:20:03 +02:00
...p,
2023-10-13 13:07:16 +02:00
};
2024-02-08 22:41:57 +01:00
var response = (await axios.get(url, {params})).data;
2023-10-13 13:07:16 +02:00
inner.data.value = response.data;
inner.meta.value = response.meta;
}
2024-02-08 22:41:57 +01:00
async function reloadPage(page) {
inner.meta.value.current_page = page;
await reload(false);
}
2023-10-13 13:07:16 +02:00
function create() {
single.value = JSON.parse(JSON.stringify(inner.meta.value.default));
}
function edit(model) {
single.value = JSON.parse(JSON.stringify(model));
}
async function submit() {
single.value.id ? await axios.patch(single.value.links.update, single.value) : await axios.post(inner.meta.value.links.store, single.value);
await reload();
single.value = null;
}
async function remove(model) {
await axios.delete(model.links.destroy);
await reload();
}
function can(permission) {
return inner.meta.value.can[permission];
}
2024-04-26 23:20:03 +02:00
function toFilterString(data) {
return btoa(encodeURIComponent(JSON.stringify(data)));
}
2023-10-13 13:07:16 +02:00
function requestCallback(successMessage, failureMessage) {
return {
onSuccess: () => {
this.$success(successMessage);
reload(false);
},
onFailure: () => {
this.$error(failureMessage);
reload(false);
},
preserveState: true,
};
}
2023-10-13 15:48:29 +02:00
function cancel() {
single.value = null;
}
2023-10-13 13:07:16 +02:00
startListener();
onBeforeUnmount(() => stopListener());
return {
data: inner.data,
meta: inner.meta,
single,
create,
edit,
reload,
2024-02-08 22:41:57 +01:00
reloadPage,
2023-10-13 13:07:16 +02:00
can,
requestCallback,
router,
submit,
remove,
2023-10-13 15:48:29 +02:00
cancel,
axios,
2024-04-26 23:20:03 +02:00
toFilterString,
2023-10-13 13:07:16 +02:00
};
}