1
1
import { useState , computed , useRequestFetch } from '#imports'
2
2
import type { UserSession , UserSessionComposable } from '#auth-utils'
3
3
4
- const useSessionState = ( ) => useState < UserSession > ( 'nuxt-session' , ( ) => ( { } ) )
5
- const useAuthReadyState = ( ) => useState ( 'nuxt-auth-ready' , ( ) => false )
6
-
7
4
/**
8
5
* Composable to get back the user session and utils around it.
9
6
* @see https://github.com/atinux/nuxt-auth-utils
10
7
*/
11
8
export function useUserSession ( ) : UserSessionComposable {
12
- const sessionState = useSessionState ( )
13
- const authReadyState = useAuthReadyState ( )
9
+ const sessionState = useState < UserSession > ( 'nuxt-session' , ( ) => ( { } ) )
10
+ const authReadyState = useState ( 'nuxt-auth-ready' , ( ) => false )
11
+
12
+ const clear = async ( ) => {
13
+ await $fetch ( '/api/_auth/session' , { method : 'DELETE' } )
14
+ sessionState . value = { }
15
+ }
16
+
17
+ const fetch = async ( ) => {
18
+ sessionState . value = await useRequestFetch ( ) ( '/api/_auth/session' , {
19
+ headers : {
20
+ Accept : 'text/json' ,
21
+ } ,
22
+ retry : false ,
23
+ } ) . catch ( ( ) => ( { } ) )
24
+ if ( ! authReadyState . value ) {
25
+ authReadyState . value = true
26
+ }
27
+ }
28
+
14
29
return {
15
30
ready : computed ( ( ) => authReadyState . value ) ,
16
31
loggedIn : computed ( ( ) => Boolean ( sessionState . value . user ) ) ,
@@ -20,21 +35,3 @@ export function useUserSession(): UserSessionComposable {
20
35
clear,
21
36
}
22
37
}
23
-
24
- async function fetch ( ) {
25
- const authReadyState = useAuthReadyState ( )
26
- useSessionState ( ) . value = await useRequestFetch ( ) ( '/api/_auth/session' , {
27
- headers : {
28
- Accept : 'text/json' ,
29
- } ,
30
- retry : false ,
31
- } ) . catch ( ( ) => ( { } ) )
32
- if ( ! authReadyState . value ) {
33
- authReadyState . value = true
34
- }
35
- }
36
-
37
- async function clear ( ) {
38
- await $fetch ( '/api/_auth/session' , { method : 'DELETE' } )
39
- useSessionState ( ) . value = { }
40
- }
0 commit comments