salix-front/src/composables/useArrayData.js

95 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-01-10 13:58:24 +00:00
import { ref, onUnmounted } from 'vue';
2023-01-05 13:57:47 +00:00
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');
2023-01-10 13:58:24 +00:00
if (!arrayDataStore.get(key)) {
arrayDataStore.set(key);
}
2023-01-05 13:57:47 +00:00
2023-01-10 13:58:24 +00:00
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);
2023-01-05 13:57:47 +00:00
if (typeof userOptions === 'object') {
2023-01-10 13:58:24 +00:00
Object.assign(options.value, userOptions);
2023-01-05 13:57:47 +00:00
}
2023-01-10 13:58:24 +00:00
// 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,
2023-01-05 13:57:47 +00:00
};
2023-01-10 13:58:24 +00:00
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;
2023-01-05 13:57:47 +00:00
2023-01-10 13:58:24 +00:00
hasMoreData.value = response.data.length === limit;
2023-01-05 13:57:47 +00:00
2023-01-10 13:58:24 +00:00
if (append === true) {
for (const row of response.data) store.data.push(row);
}
if (append === false) {
store.data = response.data;
}
2023-01-05 13:57:47 +00:00
}
2023-01-10 13:58:24 +00:00
async function apply({ filter, params }) {
if (filter) userFilter.value = filter;
if (params) userParams.value = params;
await fetch({ append: false });
}
2023-01-05 13:57:47 +00:00
2023-01-10 13:58:24 +00:00
async function loadMore() {
if (!hasMoreData.value) return;
2023-01-05 13:57:47 +00:00
2023-01-10 13:58:24 +00:00
options.value.skip = options.value.limit * (page.value - 1);
page.value += 1;
2023-01-05 13:57:47 +00:00
2023-01-10 13:58:24 +00:00
await fetch({ append: true });
2023-01-05 13:57:47 +00:00
}
async function refresh() {
// TODO
}
return {
fetch,
apply,
refresh,
2023-01-10 13:58:24 +00:00
loadMore,
store,
hasMoreData,
2023-01-05 13:57:47 +00:00
};
}