1- import { getErrorObject } from '@codebuff/ common/util/error '
2-
1+ import { userColumns } from '../../../ common/src/types/contracts/database '
2+ import { getErrorObject } from '../../../common/src/util/error'
33import { WEBSITE_URL } from '../constants'
44
55import type {
@@ -10,15 +10,35 @@ import type {
1010 GetUserInfoFromApiKeyOutput ,
1111 StartAgentRunFn ,
1212 UserColumn ,
13- } from '@codebuff/common/types/contracts/database'
14- import type { ParamsOf } from '@codebuff/common/types/function-params'
13+ } from '../../../common/src/types/contracts/database'
14+ import type { ParamsOf } from '../../../common/src/types/function-params'
15+
16+ const userInfoCache : Record <
17+ string ,
18+ Awaited < GetUserInfoFromApiKeyOutput < UserColumn > >
19+ > = { }
1520
1621export async function getUserInfoFromApiKey < T extends UserColumn > (
1722 params : GetUserInfoFromApiKeyInput < T > ,
1823) : GetUserInfoFromApiKeyOutput < T > {
1924 const { apiKey, fields, logger } = params
2025
21- const urlParams = new URLSearchParams ( { apiKey, fields : fields . join ( ',' ) } )
26+ if ( apiKey in userInfoCache ) {
27+ const userInfo = userInfoCache [ apiKey ]
28+ if ( userInfo === null ) {
29+ return userInfo
30+ }
31+ return Object . fromEntries (
32+ fields . map ( ( field ) => [ field , userInfo [ field ] ] ) ,
33+ ) as {
34+ [ K in ( typeof fields ) [ number ] ] : ( typeof userInfo ) [ K ]
35+ }
36+ }
37+
38+ const urlParams = new URLSearchParams ( {
39+ apiKey,
40+ fields : userColumns . join ( ',' ) ,
41+ } )
2242 const url = new URL ( `/api/v1/me?${ urlParams } ` , WEBSITE_URL )
2343
2444 try {
@@ -36,14 +56,25 @@ export async function getUserInfoFromApiKey<T extends UserColumn>(
3656 )
3757 return null
3858 }
39- return response . json ( )
59+
60+ userInfoCache [ apiKey ] = await response . json ( )
4061 } catch ( error ) {
4162 logger . error (
4263 { error : getErrorObject ( error ) , apiKey, fields } ,
4364 'getUserInfoFromApiKey error' ,
4465 )
4566 return null
4667 }
68+
69+ const userInfo = userInfoCache [ apiKey ]
70+ if ( userInfo === null ) {
71+ return userInfo
72+ }
73+ return Object . fromEntries (
74+ fields . map ( ( field ) => [ field , userInfo [ field ] ] ) ,
75+ ) as {
76+ [ K in ( typeof fields ) [ number ] ] : ( typeof userInfo ) [ K ]
77+ }
4778}
4879
4980export async function fetchAgentFromDatabase (
0 commit comments