( params: GetUserInfoFromApiKeyInput<T>, )
| 96 | } |
| 97 | |
| 98 | export async function getUserInfoFromApiKey<T extends UserColumn>( |
| 99 | params: GetUserInfoFromApiKeyInput<T>, |
| 100 | ): GetUserInfoFromApiKeyOutput<T> { |
| 101 | const { apiKey, fields, logger } = params |
| 102 | |
| 103 | const cached = userInfoCache[apiKey] |
| 104 | if (cached === null) { |
| 105 | throw createAuthError() |
| 106 | } |
| 107 | if ( |
| 108 | cached && |
| 109 | fields.every((field) => |
| 110 | Object.prototype.hasOwnProperty.call(cached, field), |
| 111 | ) |
| 112 | ) { |
| 113 | return Object.fromEntries(fields.map((field) => [field, cached[field]])) as { |
| 114 | [K in T]: CachedUserInfo[K] |
| 115 | } as Awaited<GetUserInfoFromApiKeyOutput<T>> |
| 116 | } |
| 117 | |
| 118 | const fieldsToFetch = cached |
| 119 | ? fields.filter( |
| 120 | (field) => !Object.prototype.hasOwnProperty.call(cached, field), |
| 121 | ) |
| 122 | : fields |
| 123 | |
| 124 | const urlParams = new URLSearchParams({ |
| 125 | fields: fieldsToFetch.join(','), |
| 126 | }) |
| 127 | const url = new URL(`/api/v1/me?${urlParams}`, WEBSITE_URL) |
| 128 | |
| 129 | let response: Response |
| 130 | try { |
| 131 | response = await fetchWithRetry( |
| 132 | url, |
| 133 | { |
| 134 | method: 'GET', |
| 135 | headers: { |
| 136 | Authorization: `Bearer ${apiKey}`, |
| 137 | }, |
| 138 | }, |
| 139 | logger, |
| 140 | ) |
| 141 | } catch (error) { |
| 142 | logger.error( |
| 143 | { error: getErrorObject(error), apiKey, fields }, |
| 144 | 'getUserInfoFromApiKey network error', |
| 145 | ) |
| 146 | // Network-level failure: DNS, connection refused, timeout, etc. |
| 147 | throw createNetworkError('Network request failed') |
| 148 | } |
| 149 | |
| 150 | if (response.status === 401 || response.status === 403 || response.status === 404) { |
| 151 | logger.error( |
| 152 | { apiKey, fields, status: response.status }, |
| 153 | 'getUserInfoFromApiKey authentication failed', |
| 154 | ) |
| 155 | // Don't cache auth failures - allow retry with potentially updated credentials |
no test coverage detected