import { ref, onUnmounted } from 'vue'; import axios from 'axios'; import { useArrayDataStore } from 'stores/useArrayDataStore'; const arrayDataStore = useArrayDataStore(); export function useArrayData(key, userOptions) { if (!key) throw new Error('ArrayData: A key is required to use this composable'); if (!arrayDataStore.get(key)) { arrayDataStore.set(key); } const store = arrayDataStore.get(key); const filter = ref({}); const userFilter = ref({}); const userParams = ref({}); const hasMoreData = ref(true); const options = ref({ limit: 10, skip: 0, }); const page = ref(1); if (typeof userOptions === 'object') { Object.assign(options.value, userOptions); } // if (typeof userOptions === 'object' && userOptions.filter) { // Object.assign(filter.value, userOptions.filter); // } onUnmounted(() => { if (arrayDataStore.get(key)) { arrayDataStore.clear(key); } }); async function fetch({ append = false }) { if (!options.value.url) return; const fetchFilter = { order: options.value.order, limit: options.value.limit, skip: options.value.skip, }; Object.assign(fetchFilter, userFilter.value); filter.value = fetchFilter; const requestOptions = { params: { filter: filter.value } }; const response = await axios.get(options.value.url, requestOptions); const { limit } = filter.value; hasMoreData.value = response.data.length === limit; if (append === true) { for (const row of response.data) store.data.push(row); } if (append === false) { store.data = response.data; } } async function apply({ filter, params }) { if (filter) userFilter.value = filter; if (params) userParams.value = params; await fetch({ append: false }); } async function loadMore() { if (!hasMoreData.value) return; options.value.skip = options.value.limit * (page.value - 1); page.value += 1; await fetch({ append: true }); } async function refresh() { // TODO } return { fetch, apply, refresh, loadMore, store, hasMoreData, }; }