Skip to content

Commit

Permalink
fix(composable): use same context for clear and fetch (#278)
Browse files Browse the repository at this point in the history
Resolves #273
  • Loading branch information
atinux authored Nov 11, 2024
1 parent 33686af commit 1fb081c
Showing 1 changed file with 20 additions and 23 deletions.
43 changes: 20 additions & 23 deletions src/runtime/app/composables/session.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { useState, computed, useRequestFetch } from '#imports'
import type { UserSession, UserSessionComposable } from '#auth-utils'

const useSessionState = () => useState<UserSession>('nuxt-session', () => ({}))
const useAuthReadyState = () => useState('nuxt-auth-ready', () => false)

/**
* Composable to get back the user session and utils around it.
* @see https://github.com/atinux/nuxt-auth-utils
*/
export function useUserSession(): UserSessionComposable {
const sessionState = useSessionState()
const authReadyState = useAuthReadyState()
const sessionState = useState<UserSession>('nuxt-session', () => ({}))
const authReadyState = useState('nuxt-auth-ready', () => false)

const clear = async () => {
await $fetch('/api/_auth/session', { method: 'DELETE' })
sessionState.value = {}
}

const fetch = async () => {
sessionState.value = await useRequestFetch()('/api/_auth/session', {
headers: {
Accept: 'text/json',
},
retry: false,
}).catch(() => ({}))
if (!authReadyState.value) {
authReadyState.value = true
}
}

return {
ready: computed(() => authReadyState.value),
loggedIn: computed(() => Boolean(sessionState.value.user)),
Expand All @@ -20,21 +35,3 @@ export function useUserSession(): UserSessionComposable {
clear,
}
}

async function fetch() {
const authReadyState = useAuthReadyState()
useSessionState().value = await useRequestFetch()('/api/_auth/session', {
headers: {
Accept: 'text/json',
},
retry: false,
}).catch(() => ({}))
if (!authReadyState.value) {
authReadyState.value = true
}
}

async function clear() {
await $fetch('/api/_auth/session', { method: 'DELETE' })
useSessionState().value = {}
}

0 comments on commit 1fb081c

Please sign in to comment.