first build commit
This commit is contained in:
50
src/app/api/transactions/route.ts
Normal file
50
src/app/api/transactions/route.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { auth } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { transactionQuerySchema } from '@/lib/validations/transaction'
|
||||
import { Prisma } from '@/generated/prisma/client'
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const session = await auth()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(req.url)
|
||||
const parsed = transactionQuerySchema.safeParse(Object.fromEntries(searchParams))
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: parsed.error.flatten() }, { status: 400 })
|
||||
}
|
||||
|
||||
const { accountId, dateFrom, dateTo, type, search, budgetId, page, limit } = parsed.data
|
||||
|
||||
const where: Prisma.TransactionWhereInput = {
|
||||
account: { userId: session.user.id },
|
||||
...(accountId && { accountId }),
|
||||
...(type && { type }),
|
||||
...(budgetId !== undefined && { budgetId: budgetId || null }),
|
||||
...(search && { description: { contains: search, mode: 'insensitive' } }),
|
||||
...((dateFrom || dateTo) && {
|
||||
date: {
|
||||
...(dateFrom && { gte: new Date(dateFrom) }),
|
||||
...(dateTo && { lte: new Date(dateTo + 'T23:59:59.999Z') }),
|
||||
},
|
||||
}),
|
||||
}
|
||||
|
||||
const [transactions, total] = await prisma.$transaction([
|
||||
prisma.transaction.findMany({
|
||||
where,
|
||||
include: {
|
||||
account: { select: { name: true, type: true } },
|
||||
budget: { select: { id: true, name: true, color: true } },
|
||||
},
|
||||
orderBy: { date: 'desc' },
|
||||
skip: (page - 1) * limit,
|
||||
take: limit,
|
||||
}),
|
||||
prisma.transaction.count({ where }),
|
||||
])
|
||||
|
||||
return NextResponse.json({ transactions, total, page, limit, totalPages: Math.ceil(total / limit) })
|
||||
}
|
||||
Reference in New Issue
Block a user