2023-12-19 12:46:55 +00:00
|
|
|
|
|
|
|
// Composable with all the logic to encapsulate a default content store
|
|
|
|
|
|
|
|
export const useContentStore = (mapKey = 'id') => {
|
|
|
|
|
|
|
|
const content = ref(new Map())
|
|
|
|
const loading = ref(false)
|
|
|
|
|
|
|
|
// Computed
|
|
|
|
const getAll = computed(() => {
|
|
|
|
return [...content.value.values()]
|
|
|
|
})
|
|
|
|
const getByKey = (key) => {
|
|
|
|
if (Array.isArray(key)) {
|
|
|
|
return key.map((k) => content.value.get(k)).filter((item) => item !== undefined)
|
|
|
|
}
|
|
|
|
return content.value.get(key)
|
|
|
|
}
|
|
|
|
|
2023-12-19 17:57:31 +00:00
|
|
|
const length = computed(() => content.value.size)
|
|
|
|
|
2023-12-19 12:46:55 +00:00
|
|
|
// Actions
|
|
|
|
function set(items) {
|
|
|
|
content.value = new Map
|
2023-12-19 17:57:31 +00:00
|
|
|
save(items)
|
2023-12-19 12:46:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function save(items) {
|
2023-12-22 13:59:42 +00:00
|
|
|
if (!items) return
|
2023-12-19 12:46:55 +00:00
|
|
|
if (!Array.isArray(items)) items = [items]
|
|
|
|
items.forEach((item) => {
|
|
|
|
content.value.set(item[mapKey], item)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
function remove(item) {
|
2023-12-20 17:38:43 +00:00
|
|
|
content.value.delete( typeof item === 'object' ? item[mapKey] : item)
|
2023-12-19 12:46:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function startLoading() {
|
|
|
|
loading.value = true
|
|
|
|
}
|
|
|
|
|
|
|
|
function stopLoading() {
|
|
|
|
loading.value = false
|
|
|
|
}
|
|
|
|
|
|
|
|
function resetState() {
|
|
|
|
set([])
|
|
|
|
stopLoading()
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
content,
|
|
|
|
loading,
|
|
|
|
getAll,
|
|
|
|
getByKey,
|
2023-12-19 17:57:31 +00:00
|
|
|
length,
|
2023-12-19 12:46:55 +00:00
|
|
|
set,
|
|
|
|
save,
|
|
|
|
remove,
|
|
|
|
startLoading,
|
|
|
|
stopLoading,
|
|
|
|
resetState
|
|
|
|
}
|
|
|
|
}
|