Files
Inventory/app/composables/useProfileSession.ts
Matthieu 78718b85ae refactor(composables): migrate JS composables to TypeScript (F3.2)
Convert 7 composables from JS to TS with proper type annotations:
useApi, useCustomFields, useProfileSession, useProfiles, useToast,
useMachineTypesApi, useMachines. Remove deprecated stubs
useComponentModels.js and usePieceModels.js.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 11:13:09 +01:00

87 lines
2.5 KiB
TypeScript

import { useState, useRequestHeaders, useRuntimeConfig } from '#imports'
import type { Profile } from './useProfiles'
const buildUrl = (path: string): string => {
const config = useRuntimeConfig()
const baseUrl = import.meta.server
? ((config.apiBaseUrl as string) || (config.public.apiBaseUrl as string) || '')
: ((config.public.apiBaseUrl as string) || '')
const base = baseUrl.replace(/\/$/, '')
return `${base}${path}`
}
export function useProfileSession() {
const activeProfile = useState<Profile | null>('profileSession:active', () => null)
const sessionLoaded = useState<boolean>('profileSession:loaded', () => false)
const loading = useState<boolean>('profileSession:loading', () => false)
const getSessionHeaders = (): Record<string, string> | undefined => {
if (!import.meta.server) { return undefined }
const headers = useRequestHeaders(['cookie'])
return headers?.cookie ? { cookie: headers.cookie } : undefined
}
const fetchCurrentProfile = async (): Promise<Profile | null> => {
loading.value = true
try {
activeProfile.value = await $fetch<Profile>(buildUrl('/session/profile'), {
method: 'GET',
credentials: 'include',
headers: getSessionHeaders(),
})
} catch (error) {
const err = error as { status?: number }
if (err?.status === 401) {
activeProfile.value = null
} else {
console.error('Erreur lors du chargement du profil actif', error)
activeProfile.value = null
}
} finally {
sessionLoaded.value = true
loading.value = false
}
return activeProfile.value
}
const ensureSession = (): Promise<Profile | null> => {
if (!sessionLoaded.value) {
return fetchCurrentProfile()
}
return Promise.resolve(activeProfile.value)
}
const activateProfile = async (profileId: string): Promise<void> => {
await $fetch(buildUrl('/session/profile'), {
method: 'POST',
credentials: 'include',
body: { profileId },
headers: getSessionHeaders(),
})
await fetchCurrentProfile()
}
const logout = async (): Promise<void> => {
try {
await $fetch(buildUrl('/session/profile'), {
method: 'DELETE',
credentials: 'include',
headers: getSessionHeaders(),
})
} finally {
activeProfile.value = null
sessionLoaded.value = true
}
}
return {
activeProfile,
loading,
sessionLoaded,
ensureSession,
fetchCurrentProfile,
activateProfile,
logout,
}
}