57 lines
1.4 KiB
TypeScript
57 lines
1.4 KiB
TypeScript
|
|
import type { User } from '~/types'
|
||
|
|
|
||
|
|
export const useUsers = () => {
|
||
|
|
const users = useState<User[]>('users.list', () => [])
|
||
|
|
|
||
|
|
const fetchUsers = async (): Promise<void> => {
|
||
|
|
const { data } = await $fetch('/api/users', { credentials: 'include' })
|
||
|
|
users.value = data
|
||
|
|
}
|
||
|
|
|
||
|
|
const createUser = async (payload: {
|
||
|
|
name: string
|
||
|
|
email: string
|
||
|
|
password: string
|
||
|
|
password_confirmation: string
|
||
|
|
role: 'admin' | 'staff'
|
||
|
|
}): Promise<User> => {
|
||
|
|
const { data } = await $fetch('/api/users', {
|
||
|
|
method: 'POST',
|
||
|
|
credentials: 'include',
|
||
|
|
body: payload,
|
||
|
|
})
|
||
|
|
users.value.push(data)
|
||
|
|
return data
|
||
|
|
}
|
||
|
|
|
||
|
|
const updateUser = async (
|
||
|
|
id: number,
|
||
|
|
payload: {
|
||
|
|
name: string
|
||
|
|
email: string
|
||
|
|
password?: string
|
||
|
|
password_confirmation?: string
|
||
|
|
role: 'admin' | 'staff'
|
||
|
|
}
|
||
|
|
): Promise<User> => {
|
||
|
|
const { data } = await $fetch(`/api/users/${id}`, {
|
||
|
|
method: 'PUT',
|
||
|
|
credentials: 'include',
|
||
|
|
body: payload,
|
||
|
|
})
|
||
|
|
const index = users.value.findIndex((u) => u.id === id)
|
||
|
|
if (index >= 0) users.value[index] = data
|
||
|
|
return data
|
||
|
|
}
|
||
|
|
|
||
|
|
const deleteUser = async (id: number): Promise<void> => {
|
||
|
|
await $fetch(`/api/users/${id}`, {
|
||
|
|
method: 'DELETE',
|
||
|
|
credentials: 'include',
|
||
|
|
})
|
||
|
|
users.value = users.value.filter((u) => u.id !== id)
|
||
|
|
}
|
||
|
|
|
||
|
|
return { users, fetchUsers, createUser, updateUser, deleteUser }
|
||
|
|
}
|