Deploy
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
|
||||
const BACKEND_URL = process.env.VULA_ECOMMERCE_BACKEND_URL || 'http://vula-ecommerce:9000'
|
||||
const PUB_KEY = process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY || ''
|
||||
|
||||
let cache: { data: unknown; ts: number } | null = null
|
||||
const CACHE_TTL = 5 * 60 * 1000 // 5 minutes
|
||||
|
||||
export async function GET(req: NextRequest) {
|
||||
const limit = Number(req.nextUrl.searchParams.get('limit') ?? '8')
|
||||
if (cache && Date.now() - cache.ts < CACHE_TTL) {
|
||||
return NextResponse.json(cache.data)
|
||||
}
|
||||
try {
|
||||
const regionRes = await fetch(`${BACKEND_URL}/store/regions?limit=1`, {
|
||||
headers: { 'x-publishable-api-key': PUB_KEY }, cache: 'no-store'
|
||||
})
|
||||
const regionData = regionRes.ok ? await regionRes.json() as { regions?: Array<{ id: string }> } : {}
|
||||
const regionId = regionData.regions?.[0]?.id ?? ''
|
||||
|
||||
const url = new URL(`${BACKEND_URL}/store/products`)
|
||||
url.searchParams.set('limit', '100')
|
||||
url.searchParams.set('fields', 'id,title,thumbnail,variants,metadata,created_at')
|
||||
if (regionId) url.searchParams.set('region_id', regionId)
|
||||
|
||||
const res = await fetch(url.toString(), {
|
||||
headers: { 'x-publishable-api-key': PUB_KEY }, cache: 'no-store'
|
||||
})
|
||||
if (!res.ok) return NextResponse.json({ products: [] }, { status: res.status })
|
||||
|
||||
const data = await res.json() as { products?: Array<{ metadata?: { order_count?: number }; created_at?: string }> }
|
||||
const sorted = (data.products ?? [])
|
||||
.slice()
|
||||
.sort((a, b) => {
|
||||
const aScore = (a.metadata?.order_count ?? 0)
|
||||
const bScore = (b.metadata?.order_count ?? 0)
|
||||
if (bScore !== aScore) return bScore - aScore
|
||||
return new Date(b.created_at ?? 0).getTime() - new Date(a.created_at ?? 0).getTime()
|
||||
})
|
||||
.slice(0, limit)
|
||||
|
||||
const result = { products: sorted }
|
||||
cache = { data: result, ts: Date.now() }
|
||||
return NextResponse.json(result)
|
||||
} catch {
|
||||
return NextResponse.json({ products: [] }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user