Files
supabase/apps/studio/data/api-keys/temp-api-keys-utils.ts
T
Ali WaseemandIvan Vasilov 3f6f8aa906 Fix: Use storage API for downloading files in the Dashboard (#40592)
* added ability to download files from storage api directly

* updated to rechange size

* updated test methods

* updated test suite

* updated tests

* updated to remove loops

* removed AI slop

* Updated to use single API key in mem

* Fix the memoization of the getOrRefreshTempApiKey function.

* updated imports

* updated imports

* updated to use import meta

---------

Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2025-11-19 11:56:04 -07:00

56 lines
1.6 KiB
TypeScript

import { getTemporaryAPIKey } from './temp-api-keys-query'
type ProjectRef = string
const projectApiKeys = new Map<ProjectRef, Promise<TemporaryApiKey>>()
export interface TemporaryApiKey {
apiKey: string
expiryTime: number
}
export function createTemporaryApiKey(apiKey: string, expiryInSeconds: number): TemporaryApiKey {
return {
apiKey,
expiryTime: Date.now() + expiryInSeconds * 1000,
}
}
export function isTemporaryApiKeyValid(
key: TemporaryApiKey | null | undefined
): key is TemporaryApiKey {
if (!key) return false
const now = Date.now()
const timeRemaining = key.expiryTime - now
return timeRemaining > 60000 // More than 60 seconds remaining
}
const checkOrRefreshTemporaryApiKey = async (
projectRef: ProjectRef,
existingKey: Promise<TemporaryApiKey> | undefined
): Promise<TemporaryApiKey> => {
const resolvedKey = await existingKey
if (isTemporaryApiKeyValid(resolvedKey)) {
return resolvedKey
}
const expiryInSeconds = 600
const fetchedKey = getTemporaryAPIKey({
projectRef,
expiry: expiryInSeconds,
}).then((data) => createTemporaryApiKey(data.api_key, expiryInSeconds))
return fetchedKey
}
// This function should never be marked as async, it should always return a promise.
export function getOrRefreshTemporaryApiKey(projectRef: ProjectRef): Promise<TemporaryApiKey> {
const existingKey = projectApiKeys.get(projectRef)
if (!existingKey) {
const data = checkOrRefreshTemporaryApiKey(projectRef, undefined)
projectApiKeys.set(projectRef, data)
}
return projectApiKeys.get(projectRef)!
}