-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathroute.ts
More file actions
62 lines (53 loc) · 2.04 KB
/
route.ts
File metadata and controls
62 lines (53 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { db } from "@/db"
import { investments } from "@/db/schema/finance"
import { eq } from "drizzle-orm"
import { z } from "zod"
const investmentSchema = z.object({
name: z.string().min(1, "Name is required"),
type: z.enum(["stocks", "bonds", "crypto", "mutual_funds", "etf", "other"]),
symbol: z.string().optional(),
quantity: z.number().positive("Quantity must be positive"),
purchasePrice: z.number().positive("Purchase price must be positive"),
currentPrice: z.number().positive("Current price must be positive"),
purchaseDate: z.string().optional(),
})
export async function GET() {
try {
const session = await auth.api.getSession({ headers: new Headers() })
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const userInvestments = await db
.select()
.from(investments)
.where(eq(investments.userId, session.user.id))
return NextResponse.json(userInvestments)
} catch (error) {
return NextResponse.json({ error: "Failed to fetch investments" }, { status: 500 })
}
}
export async function POST(request: NextRequest) {
try {
const session = await auth.api.getSession({ headers: new Headers() })
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const body = await request.json()
const validatedData = investmentSchema.parse(body)
const totalValue = validatedData.quantity * validatedData.currentPrice
const newInvestment = await db.insert(investments).values({
...validatedData,
totalValue,
userId: session.user.id,
id: crypto.randomUUID(),
}).returning()
return NextResponse.json(newInvestment[0], { status: 201 })
} catch (error) {
if (error instanceof z.ZodError) {
return NextResponse.json({ error: error.errors }, { status: 400 })
}
return NextResponse.json({ error: "Failed to create investment" }, { status: 500 })
}
}