refactor: use authenticateAndLoadUserInfo() instead of authenticate() and loadUserInfo() to reduce server calls

This commit is contained in:
Settel 2022-07-31 23:19:56 +02:00
parent fa53502901
commit 43f5a43202
5 changed files with 34 additions and 17 deletions

View File

@ -1,5 +1,5 @@
<template>
<div class="topbar__container">
<div v-if="userInfo" class="topbar__container">
<div class="topbar__username">
{{ userInfo.name }}
</div>
@ -25,7 +25,6 @@ const actionLogout = async () => {
await useAuth().logout()
useRouter().push('/')
}
</script>
<style lang="scss">

View File

@ -4,21 +4,14 @@ import { $fetch } from 'ohmyfetch'
export interface useAuth {
login(authCode: string): Promise<void>
logout(): Promise<void>
isAuthenticated(): Promise<boolean>
loadUserInfo(): Promise<void>
authenticateAndLoadUserInfo(): Promise<void>
}
export default (): useAuth => {
const userInfoStore = useUserinfoStore()
return {
isAuthenticated: async (): Promise<boolean> => {
return $fetch('/api/userinfo')
.then(() => true)
.catch(() => false)
},
loadUserInfo: async (): Promise<void> => {
authenticateAndLoadUserInfo: async (): Promise<void> => {
const userInfo = await $fetch('/api/userinfo')
userInfoStore.setUserInfo(userInfo)
},

View File

@ -0,0 +1,16 @@
export interface useEngine {
start(): void
stop(): void
}
export default (): useEngine => {
return {
start: (): void => {
console.log('start engine')
},
stop: (): void => {
console.log('stop engine')
},
}
}

View File

@ -24,8 +24,12 @@ import useAuth from '@/composables/useAuth'
const config = useRuntimeConfig()
if (await useAuth().isAuthenticated()) {
try {
await useAuth().authenticateAndLoadUserInfo()
useRouter().push('/play')
} catch (e) {
// nop
}
</script>

View File

@ -1,6 +1,6 @@
<template>
<div class="page-play__container">
<TopBar />
<TopBar T/>
wohoo!
</div>
</template>
@ -8,15 +8,20 @@
<script setup lang="ts">
import { useRouter } from '#app'
import useAuth from '@/composables/useAuth';
import useEngine from '@/composables/useEngine';
import { onMounted, onBeforeUnmount } from 'vue';
const { isAuthenticated, loadUserInfo } = useAuth()
const { authenticateAndLoadUserInfo } = useAuth()
const router = useRouter()
if (!await isAuthenticated()) {
try {
await authenticateAndLoadUserInfo()
} catch(e) {
router.push('/')
}
await loadUserInfo()
const { start: startEngine, stop: stopEngine } = useEngine()
onMounted(() => startEngine())
onBeforeUnmount(() => stopEngine())
</script>
<style lang="scss">