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

100% Statements 129/129
100% Branches 16/16
100% Functions 1/1
100% Lines 129/129

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 1301x 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 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 2x 2x 19x 17x 17x 17x 17x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 16x 16x 16x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 18x 18x 18x 18x 18x 26x 26x 16x 19x 19x 19x 16x 16x 16x 16x 16x 16x 16x 16x 16x 19x 3x 3x 3x 3x 3x 3x 3x 19x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { Prisma } from "@prisma/client";
import { logger } from "@/lib/logging";
import { measureApiPerformance } from "@/lib/performance";
import { getOrSet, CACHE_KEYS, CACHE_TTL } from "@/lib/core";
import { cachedJsonResponse, CACHE_PRESETS } from "@/lib/core/http-cache";
 
/**
 * GET /api/categories
 * Get all categories with product counts
 * Query params:
 * - parentOnly: true to get only top-level categories
 * - parentId: Get children of specific parent
 */
// Type for category response
interface CategoryResponse {
  id: number;
  name: string;
  products: number;
  imageUrl: string | null;
  isRefined: boolean;
  children: {
    id: number;
    name: string;
    products: number;
    imageUrl: string | null;
    isRefined: boolean;
  }[];
}
 
export async function GET(request: NextRequest) {
  const startTime = Date.now();
 
  try {
    const searchParams = request.nextUrl.searchParams;
    const parentId = searchParams.get("parentId");
 
    // Generate cache key based on query params
    // Note: parentOnly param is deprecated - we now always return hierarchical structure
    const cacheKey = parentId
      ? `categories:parent:${parentId}`
      : CACHE_KEYS.categories();
 
    // Use cached data if available
    const mapped = await getOrSet<CategoryResponse[]>(
      cacheKey,
      async () => {
        const where: Prisma.CategoryWhereInput = {};
        if (parentId) {
          // Get children of specific parent
          where.parentId = parseInt(parentId);
        } else {
          // Default: only fetch top-level categories (parentId = null)
          // This prevents child categories from appearing both at top level AND nested
          where.parentId = null;
        }
 
        // Optimized query: fetch categories with _count in a single query
        const categories = await prisma.category.findMany({
          where,
          select: {
            id: true,
            title: true,
            imageUrl: true,
            _count: {
              select: { products: true }
            },
            children: {
              select: {
                id: true,
                title: true,
                imageUrl: true,
                _count: {
                  select: { products: true }
                }
              }
            }
          },
          orderBy: { title: "asc" }
        });
 
        // Map to response format - optimized to avoid redundant data fetching
        return categories.map((cat) => {
          // Calculate total products for parent (own products + all children products)
          const childrenProducts = cat.children.reduce(
            (sum, child) => sum + child._count.products,
            0
          );
          const totalProducts = cat._count.products + childrenProducts;
 
          return {
            id: cat.id,
            name: cat.title,
            products: totalProducts,
            imageUrl: cat.imageUrl,
            isRefined: false,
            children: cat.children.map((child) => ({
              id: child.id,
              name: child.title,
              products: child._count.products,
              imageUrl: child.imageUrl,
              isRefined: false
            }))
          };
        });
      },
      CACHE_TTL.categories
    );
 
    measureApiPerformance("GET /api/categories", startTime);
 
    // Return with HTTP cache headers
    return cachedJsonResponse(
      request,
      { success: true, data: mapped },
      CACHE_PRESETS.publicStatic
    );
  } catch (error) {
    measureApiPerformance("GET /api/categories (error)", startTime);
    logger.error("Categories GET error", error instanceof Error ? error : new Error(String(error)), { category: "API" });
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to fetch categories" },
      { status: 500 }
    );
  }
}