All files / varjoliitokauppa/app/api/reviews route.ts

66.66% Statements 12/18
50% Branches 2/4
100% Functions 3/3
64.7% Lines 11/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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            1x 1x         1x                   1x                 1x 1x     1x 1x     1x   1x                   1x                  
import { NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { validateRating, validateRequired, ValidationError } from '@/lib/validation'
 
// GET /api/reviews - Get all reviews
export async function GET() {
  try {
    const reviews = await prisma.review.findMany({
      orderBy: { createdAt: 'desc' },
    })
 
    // Map to include date field
    const mappedReviews = reviews.map(review => ({
      id: review.id,
      productId: review.productId,
      author: review.author,
      rating: review.rating,
      text: review.text,
      status: review.status,
      date: review.createdAt.toISOString(),
    }))
 
    return NextResponse.json(mappedReviews)
  } catch (error) {
    console.error('Error fetching reviews:', error)
    return NextResponse.json({ error: 'Failed to fetch reviews' }, { status: 500 })
  }
}
 
// POST /api/reviews - Create a new review
export async function POST(request: Request) {
  try {
    const body = await request.json()
 
    // Validate required fields
    validateRequired(body.author, 'Author name')
    validateRequired(body.text, 'Review text')
 
    // Validate rating
    const rating = validateRating(body.rating)
 
    const review = await prisma.review.create({
      data: {
        productId: body.productId || null,
        author: body.author,
        rating,
        text: body.text,
        status: 'pending',
      },
    })
 
    return NextResponse.json(review, { status: 201 })
  } catch (error) {
    console.error('Error creating review:', error)
    if (error instanceof ValidationError) {
      return NextResponse.json({ error: error.message }, { status: 400 })
    }
    return NextResponse.json({ error: 'Failed to create review' }, { status: 500 })
  }
}