-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathroute.ts
More file actions
61 lines (53 loc) · 1.83 KB
/
route.ts
File metadata and controls
61 lines (53 loc) · 1.83 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
import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/lib/auth"
import { db } from "@/db"
import { income } from "@/db/schema/finance"
import { eq } from "drizzle-orm"
import { z } from "zod"
const incomeSchema = z.object({
amount: z.number().positive("Amount must be positive"),
source: z.enum([
"salary", "freelance", "investment", "business", "gift", "other"
]),
description: z.string().optional(),
date: z.string(),
recurring: z.boolean().default(false),
frequency: z.enum(["weekly", "monthly", "yearly"]).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 userIncome = await db
.select()
.from(income)
.where(eq(income.userId, session.user.id))
.orderBy(income.date)
return NextResponse.json(userIncome)
} catch (error) {
return NextResponse.json({ error: "Failed to fetch income" }, { 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 = incomeSchema.parse(body)
const newIncome = await db.insert(income).values({
...validatedData,
userId: session.user.id,
id: crypto.randomUUID(),
}).returning()
return NextResponse.json(newIncome[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 income" }, { status: 500 })
}
}