@@ -2,15 +2,16 @@ import db from '@codebuff/common/db'
22import * as schema from '@codebuff/common/db/schema'
33import { sql , eq , and , gte } from 'drizzle-orm'
44import { NextResponse } from 'next/server'
5+ import { unstable_cache } from 'next/cache'
56
67import { logger } from '@/util/logger'
78
8- // Force dynamic rendering to ensure fresh metrics data
9- export const dynamic = 'force-dynamic'
9+ // Cache for 60 seconds with stale-while-revalidate
1010export const revalidate = 60
1111
12- export async function GET ( ) {
13- try {
12+ // Cached function for expensive agent aggregations
13+ const getCachedAgents = unstable_cache (
14+ async ( ) => {
1415 const oneWeekAgo = new Date ( Date . now ( ) - 7 * 24 * 60 * 60 * 1000 )
1516
1617 // Get all published agents with their publisher info
@@ -246,7 +247,28 @@ export async function GET() {
246247 // Sort by weekly usage (most prominent metric)
247248 result . sort ( ( a , b ) => ( b . weekly_spent || 0 ) - ( a . weekly_spent || 0 ) )
248249
249- return NextResponse . json ( result )
250+ return result
251+ } ,
252+ [ 'agents-data' ] ,
253+ {
254+ revalidate : 60 ,
255+ tags : [ 'agents' ] ,
256+ }
257+ )
258+
259+ export async function GET ( ) {
260+ try {
261+ const result = await getCachedAgents ( )
262+
263+ const response = NextResponse . json ( result )
264+
265+ // Add cache headers for CDN and browser caching
266+ response . headers . set (
267+ 'Cache-Control' ,
268+ 'public, max-age=60, s-maxage=60, stale-while-revalidate=300'
269+ )
270+
271+ return response
250272 } catch ( error ) {
251273 logger . error ( { error } , 'Error fetching agents' )
252274 return NextResponse . json (
0 commit comments