opnform/client/stores/forms.js

83 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-12-14 15:53:05 +00:00
import {defineStore} from 'pinia'
import {useOpnFetch} from "~/composables/useOpnFetch.js";
2023-12-09 14:47:03 +00:00
2023-12-14 15:53:05 +00:00
export const formsEndpoint = '/open/workspaces/{workspaceId}/forms'
2023-12-09 14:47:03 +00:00
export let currentPage = 1
export const useFormsStore = defineStore('forms', {
state: () => ({
content: [],
loading: false
}),
getters: {
getById: (state) => (id) => {
if (state.content.length === 0) return null
return state.content.find(item => item.id === id)
},
getBySlug: (state) => (slug) => {
if (state.content.length === 0) return null
return state.content.find(item => item.slug === slug)
},
getAllTags: (state) => {
if (state.content.length === 0) return []
let allTags = []
state.content.forEach(form => {
2023-12-14 15:53:05 +00:00
if (form.tags && form.tags.length > 0) {
2023-12-09 14:47:03 +00:00
allTags = allTags.concat(form.tags)
}
})
return allTags.filter((item, i, ar) => ar.indexOf(item) === i)
}
},
actions: {
2023-12-14 15:53:05 +00:00
set(items) {
2023-12-09 14:47:03 +00:00
this.content = items
},
2023-12-14 15:53:05 +00:00
append(items) {
2023-12-09 14:47:03 +00:00
this.content = this.content.concat(items)
},
2023-12-14 15:53:05 +00:00
addOrUpdate(item) {
2023-12-09 14:47:03 +00:00
this.content = this.content.filter((val) => val.id !== item.id)
this.content.push(item)
},
2023-12-14 15:53:05 +00:00
remove(item) {
2023-12-09 14:47:03 +00:00
this.content = this.content.filter((val) => val.id !== item.id)
},
2023-12-14 15:53:05 +00:00
startLoading() {
2023-12-09 14:47:03 +00:00
this.loading = true
},
2023-12-14 15:53:05 +00:00
stopLoading() {
2023-12-09 14:47:03 +00:00
this.loading = false
},
2023-12-14 15:53:05 +00:00
resetState() {
2023-12-09 14:47:03 +00:00
this.set([])
this.stopLoading()
currentPage = 1
},
2023-12-14 15:53:05 +00:00
load(workspaceId) {
2023-12-09 14:47:03 +00:00
this.startLoading()
2023-12-14 15:53:05 +00:00
return useOpnFetch(formsEndpoint.replace('{workspaceId}', workspaceId) + '?page=' + currentPage).get().then((response) => {
if (currentPage === 1) {
2023-12-09 14:47:03 +00:00
this.set(response.data.data)
} else {
this.append(response.data.data)
}
if (currentPage < response.data.meta.last_page) {
currentPage += 1
this.load(workspaceId)
} else {
this.stopLoading()
currentPage = 1
}
})
},
2023-12-14 15:53:05 +00:00
loadIfEmpty(workspaceId) {
2023-12-09 14:47:03 +00:00
if (this.content.length === 0) {
return this.load(workspaceId)
}
this.stopLoading()
return Promise.resolve()
}
}
})