PersonAvatar.vue 900 Bytes
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useKeycloakStore } from '@/@core/stores/keycloakStore'

const keycloakStore = useKeycloakStore()

const defaultAvatarUrl = 'https://api.ui.ac.id/public/photo/male.jpg'
const avatarUrl = ref('')

async function checkImageExists(url: string) {
  return new Promise((resolve, reject) => {
    const img = new Image()

    img.onload = () => resolve(true)
    img.onerror = () => reject(false)
    img.src = url
  })
}

onMounted(async () => {
  if (keycloakStore.kodeIdentitas) {
    let imageUrl = `https://api.ui.ac.id/public/photo/${keycloakStore.kodeIdentitas}.jpg`
    const checkImageUrl = await checkImageExists(imageUrl)
    if (!checkImageUrl)
      imageUrl = defaultAvatarUrl

    avatarUrl.value = imageUrl
  }
})
</script>

<template>
  <VAvatar
    :image="avatarUrl"
    height="120"
    width="120"
  />
</template>