useRevealedSecret.ts43 lines · main
| 1 | import { useCallback, useRef, useState } from 'react' |
| 2 | |
| 3 | import { getAPIKeysById } from '@/data/api-keys/api-key-id-query' |
| 4 | |
| 5 | interface UseRevealedSecretOptions { |
| 6 | projectRef?: string |
| 7 | id?: string |
| 8 | } |
| 9 | |
| 10 | export function useRevealedSecret({ projectRef, id }: UseRevealedSecretOptions) { |
| 11 | const [data, setData] = useState<string | undefined | null>() |
| 12 | const [isLoading, setIsLoading] = useState(false) |
| 13 | const requestIdRef = useRef(0) |
| 14 | |
| 15 | const reveal = useCallback(async () => { |
| 16 | if (!projectRef || !id) return |
| 17 | |
| 18 | const requestId = ++requestIdRef.current |
| 19 | setIsLoading(true) |
| 20 | |
| 21 | try { |
| 22 | const result = await getAPIKeysById({ projectRef, id, reveal: true }) |
| 23 | if (requestId !== requestIdRef.current) return |
| 24 | setData(result.api_key) |
| 25 | return result.api_key |
| 26 | } catch (error) { |
| 27 | if (requestId !== requestIdRef.current) return |
| 28 | console.error('Failed to reveal secret key:', error) |
| 29 | throw error |
| 30 | } finally { |
| 31 | if (requestId === requestIdRef.current) { |
| 32 | setIsLoading(false) |
| 33 | } |
| 34 | } |
| 35 | }, [projectRef, id]) |
| 36 | |
| 37 | const clear = useCallback(() => { |
| 38 | requestIdRef.current++ |
| 39 | setData(undefined) |
| 40 | }, []) |
| 41 | |
| 42 | return { data, isLoading, reveal, clear } |
| 43 | } |