All files / src/app/api/admin/products/images route.ts

98.58% Statements 139/141
90.9% Branches 20/22
100% Functions 2/2
98.58% Lines 139/141

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 1421x 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 7x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 5x 7x     5x 5x 5x 7x 1x 1x 4x 4x 4x 4x 4x 7x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 5x 1x 1x 3x 3x 3x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import {
  withAdmin,
  withErrorHandling,
  successResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { } from "next-auth";
import { processProductImage, validateImageFile, getNextImageIndex, deleteProductImage } from "@/lib/image-processing";
import { Prisma } from "@prisma/client";
 
// ============================================================================
// TYPES
// ============================================================================
 
interface ImageProcessingResult {
  filename: string;
  path: string;
  size: number;
  dimensions: { width: number; height: number };
}
 
interface ProductImageUploadResponse {
  data: Prisma.ProductImageGetPayload<object>;
  file: {
    url: string;
    thumbnailUrl: string;
    fullSize: ImageProcessingResult;
    thumbnail: ImageProcessingResult;
  };
}
 
// ============================================================================
// HANDLERS
// ============================================================================
 
/**
 * POST /api/admin/products/images
 * Upload and process product image (creates both full-size and thumbnail)
 */
async function handlePost(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<ProductImageUploadResponse> | ApiErrorResponse>> {
  // Parse form data
  const formData = await request.formData();
  const file = formData.get("file") as File;
  const productId = parseInt(formData.get("productId") as string);
 
  if (!file || !productId) {
    throw ApiError.validation("Missing required fields: file, productId");
  }
 
  if (isNaN(productId)) {
    throw ApiError.invalidId("productId");
  }
 
  // Validate file
  const validation = validateImageFile(file);
  if (!validation.valid) {
    throw ApiError.validation(validation.error || "Invalid image file");
  }
 
  // Verify product exists
  const product = await prisma.product.findUnique({
    where: { id: productId } });
 
  if (!product) {
    throw ApiError.notFound("Product", productId);
  }
 
  // Get next image index
  const nextIndex = await getNextImageIndex(productId);
 
  // Convert File to Buffer
  const buffer = await file.arrayBuffer();
 
  // Process image (creates both full-size and thumbnail)
  const processed = await processProductImage(Buffer.from(buffer), {
    productId,
    imageIndex: nextIndex });
 
  // Create database record
  const productImage = await prisma.productImage.create({
    data: {
      productId,
      url: processed.url,
      thumbnailUrl: processed.thumbnailUrl,
      order: nextIndex } });
 
  return successResponse({
    data: productImage,
    file: {
      url: processed.url,
      thumbnailUrl: processed.thumbnailUrl,
      fullSize: processed.fullSize,
      thumbnail: processed.thumbnail } });
}
 
/**
 * DELETE /api/admin/products/images
 * Delete product image (removes both full-size and thumbnail files)
 */
async function handleDelete(
  request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<{ message: string }> | ApiErrorResponse>> {
  const { searchParams } = request.nextUrl;
  const imageId = parseInt(searchParams.get("id") || "0");
 
  if (!imageId || isNaN(imageId)) {
    throw ApiError.validation("Missing or invalid image id");
  }
 
  const image = await prisma.productImage.findUnique({
    where: { id: imageId } });
 
  if (!image) {
    throw ApiError.notFound("Image", imageId);
  }
 
  // Delete files from disk (both full-size and thumbnail)
  await deleteProductImage(image.url, image.thumbnailUrl);
 
  // Delete from database
  await prisma.productImage.delete({
    where: { id: imageId } });
 
  return successResponse({
    message: "Image deleted successfully" });
}
 
// ============================================================================
// EXPORTS
// ============================================================================
 
export const POST = withErrorHandling(withAdmin(handlePost));
export const DELETE = withErrorHandling(withAdmin(handleDelete));