gbmake-payload/src/app/api/public/product-recommendations/route.ts

101 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
import { getCache, setCache } from '@/lib/redis'
/**
* GET /api/public/product-recommendations
* 获取商品推荐列表数据(带缓存)
* 需要 x-store-api-key 验证
*/
export async function GET(req: NextRequest) {
try {
// 验证 API Key
const apiKey = req.headers.get('x-store-api-key')
const validApiKey = process.env.PAYLOAD_API_KEY
if (!apiKey || !validApiKey || apiKey !== validApiKey) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
// 生成缓存 key
const cacheKey = 'product-recommendations:data'
// 尝试从缓存获取
const cached = await getCache(cacheKey)
if (cached) {
return NextResponse.json({
success: true,
data: cached,
cached: true,
})
}
// 从数据库获取
const payload = await getPayload({ config })
const result = await payload.findGlobal({
slug: 'product-recommendations' as any,
depth: 3, // 填充商品和图片关联数据
})
// 如果功能未启用,返回空数据
if (!(result as any).enabled) {
const emptyData = {
enabled: false,
lists: [],
}
// 缓存空数据(较短时间)
await setCache(cacheKey, emptyData, 600) // 10 分钟
return NextResponse.json({
success: true,
data: emptyData,
cached: false,
})
}
// 获取所有列表
const lists = (result as any).lists || []
// 处理每个列表
const processedLists = lists.map((list: any) => {
const products = Array.isArray(list.products)
? list.products.filter((product: any) => product && product.status === 'published')
: []
return {
id: list.id,
title: list.title,
subtitle: list.subtitle,
products,
totalProducts: products.length,
}
})
const responseData = {
enabled: (result as any).enabled,
lists: processedLists,
totalLists: processedLists.length,
}
// 缓存结果1 小时)
await setCache(cacheKey, responseData, 3600)
return NextResponse.json({
success: true,
data: responseData,
cached: false,
})
} catch (error) {
console.error('Product recommendations API error:', error)
return NextResponse.json(
{
success: false,
error: error instanceof Error ? error.message : 'Failed to fetch product recommendations',
},
{ status: 500 },
)
}
}