56 lines
1.9 KiB
TypeScript
56 lines
1.9 KiB
TypeScript
import { useApi } from '~/composables/useApi'
|
|
import type { WeightData } from '~/services/dto/weight-data'
|
|
|
|
export interface WorkflowService<TEntity, TPayload> {
|
|
getList: (isValid?: boolean | null) => Promise<TEntity[]>
|
|
get: (id: number) => Promise<TEntity>
|
|
create: (payload: TPayload) => Promise<TEntity>
|
|
update: (id: number, payload: TPayload) => Promise<TEntity>
|
|
getWeight: () => Promise<WeightData>
|
|
}
|
|
|
|
export function createWorkflowService<TEntity, TPayload>(
|
|
apiResource: string,
|
|
toastPrefix: string
|
|
): WorkflowService<TEntity, TPayload> {
|
|
const getList = async (isValid: boolean | null = null): Promise<TEntity[]> => {
|
|
const api = useApi()
|
|
const query = isValid !== null ? { isValid } : {}
|
|
return api.get<TEntity[]>(apiResource, query, {
|
|
toastErrorKey: `errors.${toastPrefix}.list`
|
|
})
|
|
}
|
|
|
|
const get = async (id: number): Promise<TEntity> => {
|
|
const api = useApi()
|
|
return api.get<TEntity>(`${apiResource}/${id}`, {}, {
|
|
toastErrorKey: `errors.${toastPrefix}.fetch`
|
|
})
|
|
}
|
|
|
|
const create = async (payload: TPayload): Promise<TEntity> => {
|
|
const api = useApi()
|
|
return api.post<TEntity>(apiResource, payload, {
|
|
toastSuccessKey: `success.${toastPrefix}.create`,
|
|
toastErrorKey: `errors.${toastPrefix}.create`
|
|
})
|
|
}
|
|
|
|
const update = async (id: number, payload: TPayload): Promise<TEntity> => {
|
|
const api = useApi()
|
|
return api.patch<TEntity>(`${apiResource}/${id}`, payload, {
|
|
toastErrorKey: `errors.${toastPrefix}.update`,
|
|
toastSuccessKey: `success.${toastPrefix}.update`
|
|
})
|
|
}
|
|
|
|
const getWeight = async (): Promise<WeightData> => {
|
|
const api = useApi()
|
|
return api.get<WeightData>(`${apiResource}/weigh`, {}, {
|
|
toastErrorKey: `errors.${toastPrefix}.weigh`
|
|
})
|
|
}
|
|
|
|
return { getList, get, create, update, getWeight }
|
|
}
|