51 lines
1015 B
TypeScript
51 lines
1015 B
TypeScript
import { defineStore } from 'pinia'
|
|
import { ref } from 'vue'
|
|
import { ApiError, useApi } from '@/composables/useApi'
|
|
|
|
export type SessionStatus = 'idle' | 'checking' | 'ready' | 'error'
|
|
|
|
export interface Session {
|
|
verified: boolean
|
|
}
|
|
|
|
export const useSessionStore = defineStore('session', () => {
|
|
const status = ref<SessionStatus>('idle')
|
|
const session = ref<Session | null>(null)
|
|
let pending: Promise<void> | null = null
|
|
|
|
function check() {
|
|
if (pending) {
|
|
return pending
|
|
}
|
|
|
|
status.value = 'checking'
|
|
const { getMe } = useApi()
|
|
|
|
pending = getMe()
|
|
.then((result) => {
|
|
session.value = result
|
|
status.value = 'ready'
|
|
})
|
|
.catch((error) => {
|
|
if (error instanceof ApiError && error.status === 401) {
|
|
session.value = null
|
|
status.value = 'ready'
|
|
return
|
|
}
|
|
status.value = 'error'
|
|
})
|
|
.finally(() => {
|
|
pending = null
|
|
})
|
|
|
|
return pending
|
|
}
|
|
|
|
function retry() {
|
|
status.value = 'idle'
|
|
return check()
|
|
}
|
|
|
|
return { status, session, check, retry }
|
|
})
|