adrema/resources/js/composables/useApiIndex.js

110 lines
2.6 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';
2024-06-27 18:14:19 +02:00
export function useApiIndex(firstUrl, siteName = null) {
2023-10-13 13:07:16 +02:00
const axios = inject('axios');
2024-06-27 18:14:19 +02:00
if (siteName !== null) {
var {startListener, stopListener} = useQueueEvents(siteName, () => reload());
}
2023-10-13 13:07:16 +02:00
const single = ref(null);
2024-06-21 00:25:14 +02:00
const url = ref(firstUrl);
2023-10-13 13:07:16 +02:00
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-06-21 00:25:14 +02:00
var response = (await axios.get(url.value, {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;
}
2024-06-21 00:25:14 +02:00
function updateUrl(newUrl) {
url.value = newUrl;
}
2024-06-27 18:14:19 +02:00
if (siteName !== null) {
startListener();
onBeforeUnmount(() => stopListener());
}
2023-10-13 13:07:16 +02:00
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,
2024-06-21 00:25:14 +02:00
updateUrl,
url,
2023-10-13 13:07:16 +02:00
};
}