File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -111,9 +111,26 @@ export async function random(query: string | null = null): Promise<PostSummary |
111111 id = post ?. id || null ;
112112 } else {
113113 const key = getCacheKey ( query ) ;
114- const cachePage = await getCachedPosts ( key ) ;
115-
116- id = cachePage . posts [ Math . floor ( Math . random ( ) * cachePage . posts . length ) ] || null ;
114+
115+ key . offset = 0 ;
116+ const firstPage = await getCachedPosts ( key ) ;
117+ const total = firstPage . total ;
118+
119+ if ( total === 0 ) {
120+ id = null ;
121+ } else {
122+ // Pick a random position across the entire result set
123+ const randomPosition = Math . floor ( Math . random ( ) * total ) ;
124+
125+ // Calculate which cache page contains this position
126+ const cacheStart = Math . floor ( randomPosition / CACHE_SIZE ) * CACHE_SIZE ;
127+ key . offset = cacheStart ;
128+ const cachePage = await getCachedPosts ( key ) ;
129+
130+ // Get the post at the random position within this page
131+ const indexInPage = randomPosition - cacheStart ;
132+ id = cachePage . posts [ indexInPage ] || null ;
133+ }
117134 }
118135
119136 const post : PostSummary | null = await db . queryFirst ( SQL `
You can’t perform that action at this time.
0 commit comments