Files
Ivan Vasilov 8ce41157a3 fix: Generate temp API keys when doing mutations for Analytics buckets (#40680)
* Refactor the iceberg queries and mutations to use getOrRefreshTemporaryApiKey.

* Fix the uses of the mutations.

* Hardcode the temp api keys queries at 60 seconds.
2025-11-21 21:47:29 +08:00

54 lines
1.6 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { handleError, post } from 'data/fetchers'
import type { ResponseError, UseCustomQueryOptions } from 'types'
import { apiKeysKeys } from './keys'
interface getTemporaryAPIKeyVariables {
projectRef?: string
/** In seconds, max: 3600 (an hour) */
expiry?: number
}
// Used in storage explorer, realtime inspector and OAuth Server apps.
export async function getTemporaryAPIKey(
{ projectRef, expiry = 300 }: getTemporaryAPIKeyVariables,
signal?: AbortSignal
) {
if (!projectRef) throw new Error('projectRef is required')
const { data, error } = await post('/platform/projects/{ref}/api-keys/temporary', {
params: {
path: { ref: projectRef },
query: {
authorization_exp: expiry.toString(),
claims: JSON.stringify({ role: 'service_role' }),
},
},
signal,
})
if (error) handleError(error)
return data
}
export type TemporaryAPIKeyData = Awaited<ReturnType<typeof getTemporaryAPIKey>>
export const useTemporaryAPIKeyQuery = <TData = TemporaryAPIKeyData>(
{ projectRef }: { projectRef?: string },
{
enabled = true,
...options
}: UseCustomQueryOptions<TemporaryAPIKeyData, ResponseError, TData> = {}
) => {
// The expiry time is set to 60 seconds in the API.
const expiry = 60
return useQuery<TemporaryAPIKeyData, ResponseError, TData>({
queryKey: apiKeysKeys.temporary(projectRef),
queryFn: ({ signal }) => getTemporaryAPIKey({ projectRef, expiry }, signal),
enabled: enabled && typeof projectRef !== 'undefined',
refetchInterval: expiry * 1000, // convert to ms
...options,
})
}