51 lines
1.2 KiB
JavaScript
51 lines
1.2 KiB
JavaScript
import { defineStore } from 'pinia'
|
|
import { api } from '../lib/api'
|
|
|
|
let refreshPromise = null
|
|
|
|
export const useAuthStore = defineStore('auth', {
|
|
state: () => ({
|
|
user: null,
|
|
status: 'idle',
|
|
hydrated: false,
|
|
}),
|
|
actions: {
|
|
async refresh() {
|
|
if (refreshPromise) return refreshPromise
|
|
this.status = 'loading'
|
|
refreshPromise = (async () => {
|
|
try {
|
|
const data = await api.me()
|
|
this.user = data.user
|
|
return this.user
|
|
} catch (error) {
|
|
this.user = null
|
|
return null
|
|
} finally {
|
|
this.status = 'idle'
|
|
this.hydrated = true
|
|
refreshPromise = null
|
|
}
|
|
})()
|
|
return refreshPromise
|
|
},
|
|
async signup(email, password) {
|
|
const user = await api.signup({ email, password })
|
|
this.user = user
|
|
this.hydrated = true
|
|
return user
|
|
},
|
|
async login(email, password) {
|
|
const user = await api.login({ email, password })
|
|
this.user = user
|
|
this.hydrated = true
|
|
return user
|
|
},
|
|
async logout() {
|
|
await api.logout()
|
|
this.user = null
|
|
this.hydrated = true
|
|
},
|
|
},
|
|
})
|