@@ -50,6 +50,59 @@ async function getLastConnectTs(): Promise<Date | undefined> {
5050 return new Date ( lastConnect )
5151}
5252
53+ const TOKEN_CONNECTION_IDS_CACHE_KEY = 'tokenConnectionIds'
54+ const TOKEN_CONNECTION_IDS_TTL = 30 * 24 * 60 * 60 // 30 days
55+
56+ async function getGithubTokenConnectionIds ( ) : Promise < string [ ] > {
57+ const redisCache = new RedisCache ( 'nangoGh' , svc . redis , svc . log )
58+
59+ // Try cache first
60+ try {
61+ const cached = await redisCache . get ( TOKEN_CONNECTION_IDS_CACHE_KEY )
62+ if ( cached ) {
63+ const ids = JSON . parse ( cached ) as string [ ]
64+ if ( ids . length > 0 ) {
65+ svc . log . info ( { count : ids . length } , 'Using cached github token connection IDs' )
66+ return ids
67+ }
68+ }
69+ } catch ( err ) {
70+ svc . log . warn ( { err } , 'Failed to read token connection IDs from cache, falling back to API' )
71+ }
72+
73+ // Cache miss - fetch from Nango
74+ const allConnections = await getNangoConnections ( )
75+ const tokenIds = allConnections
76+ . filter (
77+ ( c ) =>
78+ c . provider_config_key === NangoIntegration . GITHUB &&
79+ c . connection_id . toLowerCase ( ) . startsWith ( 'github-token-' ) ,
80+ )
81+ . map ( ( c ) => c . connection_id )
82+
83+ // Store in cache
84+ if ( tokenIds . length > 0 ) {
85+ try {
86+ await redisCache . set (
87+ TOKEN_CONNECTION_IDS_CACHE_KEY ,
88+ JSON . stringify ( tokenIds ) ,
89+ TOKEN_CONNECTION_IDS_TTL ,
90+ )
91+ svc . log . info ( { count : tokenIds . length } , 'Cached github token connection IDs' )
92+ } catch ( err ) {
93+ svc . log . warn ( { err } , 'Failed to cache token connection IDs' )
94+ }
95+ }
96+
97+ return tokenIds
98+ }
99+
100+ export async function invalidateGithubTokenConnectionIdsCache ( ) : Promise < void > {
101+ const redisCache = new RedisCache ( 'nangoGh' , svc . redis , svc . log )
102+ await redisCache . delete ( TOKEN_CONNECTION_IDS_CACHE_KEY )
103+ svc . log . info ( 'Invalidated github token connection IDs cache' )
104+ }
105+
53106export async function canCreateGithubConnection ( ) : Promise < boolean > {
54107 const minutes = Number ( process . env . CROWD_MINUTES_BETWEEN_GH_NANGO_CONNECTION || 6 )
55108
@@ -360,15 +413,7 @@ export async function createGithubConnection(
360413
361414 await initNangoCloudClient ( )
362415
363- const allNangoConnections = await getNangoConnections ( )
364-
365- const tokenConnectionIds = allNangoConnections
366- . filter (
367- ( c ) =>
368- c . provider_config_key === NangoIntegration . GITHUB &&
369- c . connection_id . toLowerCase ( ) . startsWith ( 'github-token-' ) ,
370- )
371- . map ( ( c ) => c . connection_id )
416+ const tokenConnectionIds = await getGithubTokenConnectionIds ( )
372417
373418 if ( tokenConnectionIds . length === 0 ) {
374419 throw new Error ( 'No github token connections found!' )
0 commit comments