68 lines
1.8 KiB
JavaScript
68 lines
1.8 KiB
JavaScript
import { useState, useRequestHeaders, useRuntimeConfig } from '#imports'
|
|
|
|
const buildUrl = (path) => {
|
|
const config = useRuntimeConfig()
|
|
const base = config.public.apiBaseUrl?.replace(/\/$/, '') || ''
|
|
return `${base}${path}`
|
|
}
|
|
|
|
export function useProfiles () {
|
|
const profiles = useState('profiles:list', () => [])
|
|
const loadingProfiles = useState('profiles:loading', () => false)
|
|
const profilesLoaded = useState('profiles:loaded', () => false)
|
|
|
|
const getSessionHeaders = () => {
|
|
if (!process.server) { return undefined }
|
|
const headers = useRequestHeaders(['cookie'])
|
|
return headers?.cookie ? { cookie: headers.cookie } : undefined
|
|
}
|
|
|
|
const fetchProfiles = async () => {
|
|
loadingProfiles.value = true
|
|
try {
|
|
profiles.value = await $fetch(buildUrl('/session/profiles'), {
|
|
method: 'GET',
|
|
credentials: 'include',
|
|
headers: getSessionHeaders()
|
|
})
|
|
profilesLoaded.value = true
|
|
} catch (error) {
|
|
console.error('Erreur lors du chargement des profils', error)
|
|
profiles.value = []
|
|
profilesLoaded.value = false
|
|
} finally {
|
|
loadingProfiles.value = false
|
|
}
|
|
return profiles.value
|
|
}
|
|
|
|
const createProfile = async ({ firstName, lastName }) => {
|
|
const profile = await $fetch(buildUrl('/session/profiles'), {
|
|
method: 'POST',
|
|
credentials: 'include',
|
|
body: { firstName, lastName },
|
|
headers: getSessionHeaders()
|
|
})
|
|
await fetchProfiles()
|
|
return profile
|
|
}
|
|
|
|
const deleteProfile = async (profileId) => {
|
|
await $fetch(buildUrl(`/session/profiles/${profileId}`), {
|
|
method: 'DELETE',
|
|
credentials: 'include',
|
|
headers: getSessionHeaders()
|
|
})
|
|
await fetchProfiles()
|
|
}
|
|
|
|
return {
|
|
profiles,
|
|
loadingProfiles,
|
|
profilesLoaded,
|
|
fetchProfiles,
|
|
createProfile,
|
|
deleteProfile
|
|
}
|
|
}
|