diff --git a/web/lib/api.ts b/web/lib/api.ts index 168aedc8..41faf4b0 100644 --- a/web/lib/api.ts +++ b/web/lib/api.ts @@ -1,4 +1,5 @@ import {API, APIParams, APIPath} from 'common/api/schema' +import {APIError} from 'common/api/utils' import {debug} from 'common/logger' import {typedAPICall} from 'common/util/api' import {sleep} from 'common/util/time' @@ -6,18 +7,36 @@ import {sleep} from 'common/util/time' import {auth} from './firebase/users' export async function api
(path: P, params: APIParams
= {}) { - // If the api is authed and the user is not loaded, wait for the user to load. - if (API[path].authed && !auth.currentUser) { + const {authed} = API[path] + + try { + if (authed) { + if (auth.currentUser === undefined) { + // Auth hasn't resolved yet — this is a bug in the caller, not a recoverable state + console.error( + `api('${path}') called before auth resolved — check the calling hook/component`, + ) + throw new APIError(401, 'Auth not resolved yet') + } + + if (auth.currentUser === null) { + // User is definitely not logged in + console.error(`api('${path}') called while unauthenticated`) + throw new APIError(401, 'Not authenticated') + } + } + } catch (e) { + // Remove try / catch once all hooks/components are fixed + console.error('Need to fix this before removing try / catch', e) let i = 0 while (!auth.currentUser) { i++ - await sleep(i * 10) - if (i > 300) { - console.error('User did not load after 300 iterations') - break + await sleep(i * 500) + if (i > 5) { + console.error('User did not load after 5 iterations') + throw new APIError(401, 'Not authenticated') } } - debug('User loaded after', i, 'iterations') } return typedAPICall(path, params, auth.currentUser)