计数更新

This commit is contained in:
龟男日记\www 2026-02-23 00:22:12 +08:00
parent 63620571a2
commit c6771a7098
2 changed files with 76 additions and 1 deletions

View File

@ -0,0 +1,72 @@
import { NextRequest, NextResponse } from 'next/server'
import { getPayload } from 'payload'
import config from '@payload-config'
/**
* POST /api/preorders/increment-count
* orderCount Medusa subscriber
*
* Body: { medusaId: string; increment: number }
* Auth: x-payload-api-key header
*/
export async function POST(req: NextRequest) {
const apiKey = req.headers.get('x-payload-api-key')
if (!apiKey || apiKey !== process.env.PAYLOAD_API_KEY) {
return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 })
}
try {
const { medusaId, increment } = await req.json()
if (!medusaId || typeof increment !== 'number') {
return NextResponse.json(
{ success: false, error: 'medusaId 和 increment (number) 为必填' },
{ status: 400 },
)
}
const payload = await getPayload({ config })
// 查找对应的预购商品
const result = await payload.find({
collection: 'preorder-products',
where: { medusaId: { equals: medusaId } },
limit: 1,
})
const product = result.docs[0]
if (!product) {
return NextResponse.json(
{ success: false, error: `未找到 medusaId=${medusaId} 的预购商品` },
{ status: 404 },
)
}
const currentCount = typeof product.orderCount === 'number' ? product.orderCount : 0
const newCount = Math.max(0, currentCount + increment)
await payload.update({
collection: 'preorder-products',
id: product.id,
data: { orderCount: newCount },
})
console.log(
`[increment-count] ✅ ${product.title}: ${currentCount}${newCount} (+${increment})`,
)
return NextResponse.json({
success: true,
title: product.title,
previousCount: currentCount,
newCount,
increment,
})
} catch (error: any) {
console.error('[increment-count] ❌', error?.message)
return NextResponse.json(
{ success: false, error: error?.message || 'Unknown error' },
{ status: 500 },
)
}
}

View File

@ -141,7 +141,10 @@ export async function GET(request: NextRequest) {
// 新建 // 新建
await payload.create({ await payload.create({
collection: targetCollection, collection: targetCollection,
data: { ...productData }, data: {
...productData,
status: (productData.status as 'draft' | 'published') ?? 'draft',
},
}) })
results.created++ results.created++
} }