Files
soul/app/api/user/update/route.ts

73 lines
1.8 KiB
TypeScript
Raw Normal View History

// app/api/user/update/route.ts
// 更新用户信息(头像、昵称等)
import { NextRequest, NextResponse } from 'next/server'
import { getDb } from '@/lib/db'
export async function POST(req: NextRequest) {
try {
const { userId, nickname, avatar, phone, wechatId, address } = await req.json()
if (!userId) {
return NextResponse.json({ error: '缺少用户ID' }, { status: 400 })
}
const db = await getDb()
// 构建更新字段
const updates: string[] = []
const values: any[] = []
if (nickname !== undefined) {
updates.push('nickname = ?')
values.push(nickname)
}
if (avatar !== undefined) {
updates.push('avatar = ?')
values.push(avatar)
}
if (phone !== undefined) {
updates.push('phone = ?')
values.push(phone)
}
if (wechatId !== undefined) {
updates.push('wechat_id = ?')
values.push(wechatId)
}
if (address !== undefined) {
updates.push('address = ?')
values.push(address)
}
if (updates.length === 0) {
return NextResponse.json({ error: '没有要更新的字段' }, { status: 400 })
}
updates.push('updated_at = NOW()')
values.push(userId)
const sql = `UPDATE users SET ${updates.join(', ')} WHERE id = ?`
await db.execute(sql, values)
// 返回更新后的用户信息
const [rows] = await db.execute(
'SELECT id, nickname, avatar, phone, wechat_id, address FROM users WHERE id = ?',
[userId]
)
const user = (rows as any[])[0]
return NextResponse.json({
success: true,
user
})
} catch (error) {
console.error('[User Update] Error:', error)
return NextResponse.json(
{ error: '更新用户信息失败' },
{ status: 500 }
)
}
}