36 lines
1016 B
TypeScript
36 lines
1016 B
TypeScript
|
|
import type {Material, MaterialsState} from "~/stores/materials/types.materials";
|
||
|
|
import { orderBy } from 'lodash-es'
|
||
|
|
import dayjs from "dayjs";
|
||
|
|
|
||
|
|
export const useMaterialsStore = defineStore('materials', {
|
||
|
|
state: (): MaterialsState => ({
|
||
|
|
isLoadingMaterials: false,
|
||
|
|
errorMaterials: null,
|
||
|
|
materials: [],
|
||
|
|
}),
|
||
|
|
|
||
|
|
getters: {
|
||
|
|
getMaterialsSorted: (state) => orderBy(state.materials, (item) => dayjs(item.datetime).valueOf(), 'desc'),
|
||
|
|
getById: (state) => (id:string): Material | undefined => state.materials.find(item => item.id === +id)
|
||
|
|
},
|
||
|
|
|
||
|
|
actions: {
|
||
|
|
async fetchMaterials() {
|
||
|
|
this.isLoadingMaterials = true
|
||
|
|
this.errorMaterials = null
|
||
|
|
try {
|
||
|
|
const {data} = await useFetch<Material[]>('/api', {key: 'fetch-materials'})
|
||
|
|
if (data.value) {
|
||
|
|
this.materials = data.value
|
||
|
|
}
|
||
|
|
} catch (e) {
|
||
|
|
console.log('Error:', e)
|
||
|
|
this.errorMaterials = String(e)
|
||
|
|
} finally {
|
||
|
|
this.isLoadingMaterials = false
|
||
|
|
}
|
||
|
|
},
|
||
|
|
|
||
|
|
}
|
||
|
|
})
|