pummmp.fun/app/api/users/[username]/route.ts
2026-07-04 12:49:09 -07:00

63 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { connectToDatabase } from '@/lib/mongodb'
import { ObjectId } from 'mongodb'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ username: string }> }
) {
try {
const { username } = await params
const decodedUsername = decodeURIComponent(username)
const { db } = await connectToDatabase()
const user = await db.collection('users').findOne(
{ name: { $regex: new RegExp(`^${decodedUsername}$`, 'i') } },
{ projection: { email: 0, discordId: 0, balance: 0 } }
)
if (!user) {
return NextResponse.json({ error: 'User not found' }, { status: 404 })
}
const createdCoins = await db
.collection('coins')
.find({ creatorId: user._id.toString() })
.sort({ createdAt: -1 })
.toArray()
let portfolioValue = 0
const portfolio = user.portfolio || []
const portfolioWithData = []
for (const item of portfolio) {
if (item.amount > 0) {
const coin = await db.collection('coins').findOne({ _id: new ObjectId(item.coinId) })
if (coin) {
const value = item.amount * coin.price
portfolioValue += value
portfolioWithData.push({
...item,
coin,
currentValue: value
})
}
}
}
portfolioWithData.sort((a, b) => b.currentValue - a.currentValue)
return NextResponse.json({
user: {
...user,
portfolioValue,
coinsCreated: createdCoins.length
},
createdCoins,
portfolio: portfolioWithData
})
} catch (error) {
console.error('Error fetching user profile:', error)
return NextResponse.json({ error: 'Failed to fetch user profile' }, { status: 500 })
}
}