All files / src/app/api/cart route.ts

100% Statements 169/169
94.11% Branches 16/17
100% Functions 2/2
100% Lines 169/169

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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 1701x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 3x 3x 6x 6x 6x 6x 6x 6x 6x 5x 9x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 4x 4x 1x 1x 1x  
import { NextRequest } from "next/server";
import {
  withAuth,
  withErrorHandling,
  successResponse,
  createdResponse,
  validationErrorResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse
} from "@/lib/api";
import { prisma } from "@/lib/prisma";
import { addToCartSchema, validateInput } from "@/lib/validation-schemas";
import { Session } from "next-auth";
import { RouteContext } from "@/lib/api/middleware";
import { NextResponse } from "next/server";
 
// Type for cart item with product images
interface CartItemWithProduct {
  id: number;
  quantity: number;
  product: {
    id: number;
    title: string;
    price: number;
    discountedPrice: number | null;
    images: Array<{ thumbnailUrl: string | null; url: string }>;
  };
}
 
interface CartResponse {
  items: Array<{
    id: number;
    title: string;
    price: number;
    discountedPrice: number | null;
    quantity: number;
    imgs: {
      thumbnails: string[];
      previews: string[];
    };
  }>;
  syncedAt: string;
  deviceId: string;
}
 
// GET /api/cart - Get user's cart items
async function handleGet(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<CartResponse>>> {
  const userId = session.user.id;
  const deviceId = request.headers.get("x-device-id") || "default";
 
  const cartItems = await prisma.cart.findMany({
    where: { userId },
    include: {
      product: {
        include: {
          images: {
            orderBy: { order: "asc" }
          }
        }
      }
    },
    orderBy: { updatedAt: "desc" }
  });
 
  // Transform to match frontend CartItem type
  const transformedCart = cartItems.map((item: CartItemWithProduct) => ({
    id: item.product.id,
    title: item.product.title,
    price: item.product.price,
    discountedPrice: item.product.discountedPrice,
    quantity: item.quantity,
    imgs: {
      thumbnails: item.product.images.map((img) => img.thumbnailUrl || img.url),
      previews: item.product.images.map((img) => img.url)
    }
  }));
 
  return successResponse({
    items: transformedCart,
    syncedAt: new Date().toISOString(),
    deviceId
  });
}
 
// POST /api/cart - Add item to cart
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const body = await request.json();
  const userId = session.user.id;
  const deviceId = request.headers.get("x-device-id") || "default";
 
  // Validate input
  const validation = validateInput(addToCartSchema, body);
  if (!validation.success) {
    return validationErrorResponse("Validation failed", validation.errors);
  }
 
  const { productId, quantity } = validation.data!;
 
  // Check if product exists
  const product = await prisma.product.findUnique({
    where: { id: productId }
  });
 
  if (!product) {
    throw ApiError.notFound("Product");
  }
 
  // Check if item already in cart
  const existingCartItem = await prisma.cart.findUnique({
    where: {
      userId_productId: {
        userId,
        productId
      }
    }
  });
 
  let cartItem;
  if (existingCartItem) {
    // Update quantity and sync info
    cartItem = await prisma.cart.update({
      where: { id: existingCartItem.id },
      data: {
        quantity: existingCartItem.quantity + quantity,
        deviceId,
        syncedAt: new Date()
      },
      include: {
        product: {
          include: {
            images: true
          }
        }
      }
    });
  } else {
    // Create new cart item
    cartItem = await prisma.cart.create({
      data: {
        userId,
        productId,
        quantity,
        deviceId,
        syncedAt: new Date()
      },
      include: {
        product: {
          include: {
            images: true
          }
        }
      }
    });
  }
 
  return createdResponse(cartItem);
}
 
export const GET = withErrorHandling(withAuth(handleGet));
export const POST = withErrorHandling(withAuth(handlePost));