69 lines
2.5 KiB
TypeScript
69 lines
2.5 KiB
TypeScript
|
|
/**
|
|||
|
|
* 用户收货地址 - 列表与新建
|
|||
|
|
* GET: 列表(需 userId)
|
|||
|
|
* POST: 新建(必填 userId, name, phone, detail;省/市/区可选)
|
|||
|
|
*/
|
|||
|
|
|
|||
|
|
import { NextRequest, NextResponse } from 'next/server'
|
|||
|
|
import { query } from '@/lib/db'
|
|||
|
|
import { randomUUID } from 'crypto'
|
|||
|
|
|
|||
|
|
export async function GET(request: NextRequest) {
|
|||
|
|
try {
|
|||
|
|
const userId = request.nextUrl.searchParams.get('userId')
|
|||
|
|
if (!userId) {
|
|||
|
|
return NextResponse.json({ success: false, message: '缺少 userId' }, { status: 400 })
|
|||
|
|
}
|
|||
|
|
const rows = await query(
|
|||
|
|
`SELECT id, user_id, name, phone, province, city, district, detail, is_default, created_at, updated_at
|
|||
|
|
FROM user_addresses WHERE user_id = ? ORDER BY is_default DESC, updated_at DESC`,
|
|||
|
|
[userId]
|
|||
|
|
) as any[]
|
|||
|
|
const list = (rows || []).map((r) => ({
|
|||
|
|
id: r.id,
|
|||
|
|
userId: r.user_id,
|
|||
|
|
name: r.name,
|
|||
|
|
phone: r.phone,
|
|||
|
|
province: r.province,
|
|||
|
|
city: r.city,
|
|||
|
|
district: r.district,
|
|||
|
|
detail: r.detail,
|
|||
|
|
isDefault: !!r.is_default,
|
|||
|
|
fullAddress: `${r.province}${r.city}${r.district}${r.detail}`,
|
|||
|
|
createdAt: r.created_at,
|
|||
|
|
updatedAt: r.updated_at,
|
|||
|
|
}))
|
|||
|
|
return NextResponse.json({ success: true, list })
|
|||
|
|
} catch (e) {
|
|||
|
|
console.error('[Addresses] GET error:', e)
|
|||
|
|
return NextResponse.json({ success: false, message: '获取地址列表失败' }, { status: 500 })
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
export async function POST(request: NextRequest) {
|
|||
|
|
try {
|
|||
|
|
const body = await request.json()
|
|||
|
|
const { userId, name, phone, province, city, district, detail, isDefault } = body
|
|||
|
|
if (!userId || !name || !phone || !detail) {
|
|||
|
|
return NextResponse.json(
|
|||
|
|
{ success: false, message: '缺少必填项:userId, name, phone, detail' },
|
|||
|
|
{ status: 400 }
|
|||
|
|
)
|
|||
|
|
}
|
|||
|
|
const id = randomUUID().replace(/-/g, '').slice(0, 24)
|
|||
|
|
const p = (v: string | undefined) => (v == null ? '' : String(v).trim())
|
|||
|
|
if (isDefault) {
|
|||
|
|
await query('UPDATE user_addresses SET is_default = 0 WHERE user_id = ?', [userId])
|
|||
|
|
}
|
|||
|
|
await query(
|
|||
|
|
`INSERT INTO user_addresses (id, user_id, name, phone, province, city, district, detail, is_default)
|
|||
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|||
|
|
[id, userId, name.trim(), phone.trim(), p(province), p(city), p(district), detail.trim(), isDefault ? 1 : 0]
|
|||
|
|
)
|
|||
|
|
return NextResponse.json({ success: true, id, message: '添加成功' })
|
|||
|
|
} catch (e) {
|
|||
|
|
console.error('[Addresses] POST error:', e)
|
|||
|
|
return NextResponse.json({ success: false, message: '添加地址失败' }, { status: 500 })
|
|||
|
|
}
|
|||
|
|
}
|