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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 1x 1x 9x 9x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 9x 9x 10x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 10x 1x 1x 1x 1x 1x 9x 10x 1x 1x 1x 1x 9x 9x 9x 9x 10x 1x 1x 10x 9x 9x 9x 9x 9x 10x 10x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 1x 2x 2x 1x 5x 5x 5x 5x 2x 2x 2x 2x 2x 2x 2x 1x 1x | export const dynamic = "force-dynamic";
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from "@/lib/prisma";
import {
withErrorHandling,
withAdmin,
ApiError,
ApiSuccessResponse,
createdResponse,
type RouteContext } from "@/lib/api";
import { createProductSchema, validateInput } from "@/lib/validation-schemas";
import { invalidatePattern } from "@/lib/core";
import { checkRateLimit, rateLimitPresets } from "@/lib/security";
import { addSecurityHeaders } from "@/lib/security";
import { Prisma } from "@prisma/client";
import { transformDBProductsToLegacy, DBProductWithRelations } from "@/lib/ecommerce";
import { measureApiPerformance } from "@/lib/performance";
import { cachedJsonResponse, CACHE_PRESETS } from "@/lib/core/http-cache";
// GET /api/products - List all products with pagination and filtering
async function handleGet(
request: NextRequest
): Promise<NextResponse<ApiSuccessResponse<{
products: unknown[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
}>>> {
const startTime = Date.now();
// Rate limiting for API endpoint
const ip = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "unknown";
if (!checkRateLimit(`api-products-${ip}`, rateLimitPresets.standard.limit, rateLimitPresets.standard.windowMs)) {
// const rateLimitInfo = getRateLimitInfo(`api-products-${ip}`, rateLimitPresets.standard.limit);
throw ApiError.rateLimited("Rate limit exceeded");
}
const searchParams = request.nextUrl.searchParams;
const page = parseInt(searchParams.get("page") || "1");
const limit = parseInt(searchParams.get("limit") || "10");
const categoryId = searchParams.get("categoryId");
const search = searchParams.get("search");
const minPrice = searchParams.get("minPrice");
const maxPrice = searchParams.get("maxPrice");
// New query parameters for component support
const latest = searchParams.get("latest") === "true";
const bestseller = searchParams.get("bestseller") === "true";
const random = searchParams.get("random") === "true";
const exclude = searchParams.get("exclude")?.split(",").map(id => parseInt(id)) || [];
const skip = (page - 1) * limit;
// Build where clause
const where: Prisma.ProductWhereInput = {};
// Exclude specific product IDs
if (exclude.length > 0) {
where.id = { notIn: exclude };
}
// Hierarchical category filtering
if (categoryId) {
const parsedCategoryId = parseInt(categoryId);
// Fetch the category to check if it has children
const category = await prisma.category.findUnique({
where: { id: parsedCategoryId },
include: { children: true }
});
if (category) {
// If category has children, include all child category IDs
if (category.children && category.children.length > 0) {
const categoryIds = [parsedCategoryId, ...category.children.map((c: { id: number }) => c.id)];
where.categoryId = { in: categoryIds };
} else {
// No children, just filter by this category
where.categoryId = parsedCategoryId;
}
}
}
if (search) {
where.OR = [
{ title: { contains: search } },
{ description: { contains: search } },
];
}
if (minPrice || maxPrice) {
where.discountedPrice = {};
if (minPrice) where.discountedPrice.gte = parseFloat(minPrice);
if (maxPrice) where.discountedPrice.lte = parseFloat(maxPrice);
}
// Determine orderBy based on query parameters
let orderBy: Prisma.ProductOrderByWithRelationInput | Prisma.ProductOrderByWithRelationInput[] = { createdAt: "desc" };
if (bestseller) {
// Sort by review count (most reviewed first)
orderBy = { reviews: { _count: "desc" } };
} else if (latest) {
// Sort by newest first (already the default, but explicit)
orderBy = { createdAt: "desc" };
}
// Handle random selection using database-level randomization
let products: DBProductWithRelations[];
let total: number;
if (random) {
// Use raw SQL for efficient random selection
// Build WHERE clause components
const whereConditions: string[] = [];
const params: (string | number)[] = [];
if (exclude.length > 0) {
whereConditions.push(`p.id NOT IN (${exclude.map(() => '?').join(', ')})`);
params.push(...exclude);
}
if (categoryId) {
const parsedCategoryId = parseInt(categoryId);
const category = await prisma.category.findUnique({
where: { id: parsedCategoryId },
include: { children: true }
});
if (category) {
if (category.children && category.children.length > 0) {
const categoryIds = [parsedCategoryId, ...category.children.map((c: { id: number }) => c.id)];
whereConditions.push(`p.category_id IN (${categoryIds.map(() => '?').join(', ')})`);
params.push(...categoryIds);
} else {
whereConditions.push('p.category_id = ?');
params.push(parsedCategoryId);
}
}
}
const whereClause = whereConditions.length > 0 ? `WHERE ${whereConditions.join(' AND ')}` : '';
// Get random product IDs using database-level randomization
const randomIds = await prisma.$queryRawUnsafe<{ id: number }[]>(
`SELECT id FROM products ${whereClause} ORDER BY RAND() LIMIT ?`,
...params,
limit
);
if (randomIds.length > 0) {
products = await prisma.product.findMany({
where: { id: { in: randomIds.map(r => r.id) } },
include: {
category: true,
images: { orderBy: { order: "asc" } },
reviews: { select: { rating: true } } } }) as unknown as DBProductWithRelations[];
} else {
products = [];
}
// Get total count for pagination info
total = await prisma.product.count({ where });
} else {
// Standard query with pagination
[products, total] = await Promise.all([
prisma.product.findMany({
where,
skip,
take: limit,
include: {
category: true,
images: { orderBy: { order: "asc" } },
reviews: { select: { rating: true } } },
orderBy }) as unknown as Promise<DBProductWithRelations[]>,
prisma.product.count({ where }),
]);
}
// Transform products using utility function
const productsWithRatings = transformDBProductsToLegacy(products);
measureApiPerformance("GET /api/products", startTime);
// Return with HTTP cache headers
return addSecurityHeaders(
cachedJsonResponse(
request,
{
products: productsWithRatings,
pagination: {
page,
limit,
total,
totalPages: Math.ceil(total / limit) } },
CACHE_PRESETS.productList
)
) as NextResponse<ApiSuccessResponse<{
products: unknown[];
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
};
}>>;
}
export const GET = withErrorHandling(handleGet);
/* eslint-disable @typescript-eslint/no-unused-vars */
// POST /api/products - Create a new product (Admin only)
async function handlePost(
request: NextRequest,
_context: RouteContext | undefined,
_session: unknown,
_user: unknown
): Promise<NextResponse> {
/* eslint-enable @typescript-eslint/no-unused-vars */
const body = await request.json();
// Validate input
const validation = validateInput(createProductSchema, body);
if (!validation.success) {
throw ApiError.validation("Validation failed", validation.errors);
}
const {
title,
description,
price,
discountedPrice,
stock,
sku,
categoryId,
images } = validation.data!;
const product = await prisma.product.create({
data: {
title,
description,
price,
discountedPrice,
stock,
sku,
categoryId,
images: images
? {
create: images.map((img: { url: string; type: string }, index: number) => ({
url: img.url,
type: img.type as "THUMBNAIL" | "PREVIEW",
order: index })) }
: undefined },
include: {
category: true,
images: true } });
// Invalidate relevant caches
await invalidatePattern("products:*");
await invalidatePattern("categories:*");
return createdResponse(product);
}
export const POST = withErrorHandling(withAdmin(handlePost));
|