Newer
Older
navi-1 / webclient / src / stores / apiTokens.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as api from '@/api/index.js'

export const useApiTokensStore = defineStore('apiTokens', () => {
  const tokens = ref([])
  const loading = ref(false)
  const creating = ref(false)

  async function fetchTokens() {
    loading.value = true
    try {
      const data = await api.getApiTokens()
      tokens.value = data.items || []
    } finally {
      loading.value = false
    }
  }

  async function createToken(name) {
    creating.value = true
    try {
      const token = await api.createApiToken(name)
      tokens.value.unshift({
        id: token.id,
        name: token.name,
        token_prefix: token.token_prefix,
        created_at: token.created_at,
        last_used_at: null,
      })
      return token
    } finally {
      creating.value = false
    }
  }

  async function revokeToken(id) {
    await api.revokeApiToken(id)
    tokens.value = tokens.value.filter(t => t.id !== id)
  }

  return {
    tokens,
    loading,
    creating,
    fetchTokens,
    createToken,
    revokeToken,
  }
})