60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
import type { WorkflowService } from '~/services/workflow-service'
|
|
|
|
const isEntityData = (value: unknown): value is { id: number } => {
|
|
return Boolean(value && typeof value === 'object' && 'id' in value)
|
|
}
|
|
|
|
export function useWorkflowStoreLogic<TEntity extends { id: number }, TPayload>(
|
|
service: WorkflowService<TEntity, TPayload>
|
|
) {
|
|
const current = ref<TEntity | null>(null)
|
|
const isLoading = ref(false)
|
|
|
|
const setCurrent = (entity: TEntity | null) => {
|
|
current.value = entity
|
|
}
|
|
|
|
const clearCurrent = () => {
|
|
current.value = null
|
|
}
|
|
|
|
const load = async (id: number) => {
|
|
isLoading.value = true
|
|
const result = await service.get(id).finally(() => {
|
|
isLoading.value = false
|
|
})
|
|
if (!isEntityData(result)) {
|
|
current.value = null
|
|
return null
|
|
}
|
|
current.value = result as any
|
|
return result
|
|
}
|
|
|
|
const create = async (payload: TPayload) => {
|
|
isLoading.value = true
|
|
const result = await service.create(payload).finally(() => {
|
|
isLoading.value = false
|
|
})
|
|
if (!isEntityData(result)) {
|
|
return null
|
|
}
|
|
current.value = result as any
|
|
return result
|
|
}
|
|
|
|
const update = async (id: number, payload: TPayload) => {
|
|
isLoading.value = true
|
|
const result = await service.update(id, payload).finally(() => {
|
|
isLoading.value = false
|
|
})
|
|
if (!isEntityData(result)) {
|
|
return null
|
|
}
|
|
current.value = result as any
|
|
return result
|
|
}
|
|
|
|
return { current, isLoading, setCurrent, clearCurrent, load, create, update }
|
|
}
|