All files / src/lib/database dataLoaders.ts

49.61% Statements 129/260
96.66% Branches 29/30
57.14% Functions 8/14
49.61% Lines 129/260

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 2611x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x                                   11x 11x 11x         11x 11x 11x 11x                           11x 11x 11x 13x 13x 17x 13x 13x 11x 11x 11x 1x 11x 11x 11x 1x 11x 11x 1x 1x 1x 1x 5x 5x 7x 7x 7x 7x 7x 5x 5x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 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                                                                        
/**
 * DataLoader Pattern Utilities
 *
 * Provides batch loading functions to efficiently load related data
 * and avoid N+1 query problems. These loaders batch multiple requests
 * into single database queries.
 */
 
import { prisma } from '@/lib/prisma';
import type { Category, Product } from '@prisma/client';
 
/**
 * Simple batching function that collects requests and executes them together
 * This is a lightweight alternative to the dataloader library
 */
type BatchLoadFn<K, V> = (keys: readonly K[]) => Promise<(V | null)[]>;
 
interface Loader<K, V> {
  load: (key: K) => Promise<V | null>;
  loadMany: (keys: K[]) => Promise<(V | null)[]>;
  clear: (key: K) => void;
  clearAll: () => void;
}
 
function createBatchLoader<K, V>(batchFn: BatchLoadFn<K, V>): Loader<K, V> {
  const cache = new Map<K, Promise<V | null>>();
  let batch: K[] = [];
  let batchPromise: Promise<void> | null = null;
 
  const executeBatch = async () => {
    const currentBatch = [...batch];
    batch = [];
    batchPromise = null;

    if (currentBatch.length === 0) return;

    const results = await batchFn(currentBatch);

    currentBatch.forEach((key, index) => {
      const existingPromise = cache.get(key);
      if (existingPromise) {
        // The promise is already set, need to resolve it
        // This is handled by the batchFn returning results in order
      }
      // Update cache with resolved value
      cache.set(key, Promise.resolve(results[index]));
    });
  };
 
  const scheduleBatch = () => {
    if (!batchPromise) {
      batchPromise = Promise.resolve().then(executeBatch);
    }
    return batchPromise;
  };
 
  return {
    load: async (key: K): Promise<V | null> => {
      const cached = cache.get(key);
      if (cached) return cached;

      const promise = new Promise<V | null>((resolve) => {
        batch.push(key);
        scheduleBatch().then(async () => {
          const results = await batchFn([key]);
          resolve(results[0]);
        });
      });

      cache.set(key, promise);
      return promise;
    },
 
    loadMany: async (keys: K[]): Promise<(V | null)[]> => {
      const results = await batchFn(keys);
      keys.forEach((key, index) => {
        cache.set(key, Promise.resolve(results[index]));
      });
      return results;
    },
 
    clear: (key: K) => {
      cache.delete(key);
    },
 
    clearAll: () => {
      cache.clear();
    }};
}
 
/**
 * Create a category loader that batches category lookups
 */
export function createCategoryLoader(): Loader<number, Category> {
  return createBatchLoader<number, Category>(async (ids) => {
    const categories = await prisma.category.findMany({
      where: { id: { in: [...ids] } }});
 
    const categoryMap = new Map(categories.map(c => [c.id, c]));
    return ids.map(id => categoryMap.get(id) || null);
  });
}
 
/**
 * Create a review count loader that batches review count lookups
 */
export function createReviewCountLoader(): Loader<number, number> {
  return createBatchLoader<number, number>(async (productIds) => {
    const counts = await prisma.review.groupBy({
      by: ['productId'],
      where: {
        productId: { in: [...productIds] }},
      _count: true});
 
    const countMap = new Map(counts.map(c => [c.productId, c._count]));
    return productIds.map(id => countMap.get(id) ?? 0);
  });
}
 
/**
 * Create a review average loader that batches average rating lookups
 */
export function createReviewAverageLoader(): Loader<number, number> {
  return createBatchLoader<number, number>(async (productIds) => {
    const averages = await prisma.review.groupBy({
      by: ['productId'],
      where: {
        productId: { in: [...productIds] }},
      _avg: { rating: true }});
 
    const avgMap = new Map(averages.map(a => [a.productId, a._avg.rating ?? 0]));
    return productIds.map(id => avgMap.get(id) ?? 0);
  });
}
 
/**
 * Create a product loader that batches product lookups
 */
export function createProductLoader(): Loader<number, Product> {
  return createBatchLoader<number, Product>(async (ids) => {
    const products = await prisma.product.findMany({
      where: { id: { in: [...ids] } }});
 
    const productMap = new Map(products.map(p => [p.id, p]));
    return ids.map(id => productMap.get(id) || null);
  });
}
 
/**
 * Load products with their categories and review statistics
 * This is an optimized version that avoids N+1 queries
 */
export async function loadProductsWithStats(
  productIds: number[]
): Promise<Array<{
  product: Product;
  category: Category | null;
  reviewCount: number;
  averageRating: number;
}>> {
  if (productIds.length === 0) return [];

  // Execute all queries in parallel
  const [products, categories, reviewCounts, reviewAverages] = await Promise.all([
    // Get products
    prisma.product.findMany({
      where: { id: { in: productIds } }}),
    // Get categories for these products
    prisma.category.findMany({
      where: {
        products: {
          some: { id: { in: productIds } }}}}),
    // Get review counts
    prisma.review.groupBy({
      by: ['productId'],
      where: { productId: { in: productIds } },
      _count: true}),
    // Get average ratings
    prisma.review.groupBy({
      by: ['productId'],
      where: { productId: { in: productIds } },
      _avg: { rating: true }}),
  ]);

  // Build lookup maps
  const categoryMap = new Map(categories.map(c => [c.id, c]));
  const countMap = new Map(reviewCounts.map(c => [c.productId, c._count]));
  const avgMap = new Map(reviewAverages.map(a => [a.productId, a._avg.rating ?? 0]));

  // Combine results
  return products.map(product => ({
    product,
    category: categoryMap.get(product.categoryId) ?? null,
    reviewCount: countMap.get(product.id) ?? 0,
    averageRating: avgMap.get(product.id) ?? 0}));
}
 
/**
 * Load user's order statistics efficiently
 */
export async function loadUserOrderStats(
  userIds: number[]
): Promise<Map<number, { orderCount: number; totalSpent: number }>> {
  if (userIds.length === 0) return new Map();

  const stats = await prisma.order.groupBy({
    by: ['userId'],
    where: { userId: { in: userIds } },
    _count: true,
    _sum: { total: true }});

  return new Map(
    stats.map(s => [
      s.userId,
      {
        orderCount: s._count,
        totalSpent: s._sum.total ?? 0},
    ])
  );
}
 
/**
 * Load category tree with product counts efficiently
 */
export async function loadCategoryTree(): Promise<Array<{
  category: Category;
  productCount: number;
  children: Array<{ category: Category; productCount: number }>;
}>> {
  // Get all categories with product counts in a single query
  const categories = await prisma.category.findMany({
    include: {
      _count: { select: { products: true } },
      children: {
        include: {
          _count: { select: { products: true } }}}},
    where: { parentId: null }, // Only top-level categories
  });

  return categories.map(cat => ({
    category: {
      id: cat.id,
      title: cat.title,
      slug: cat.slug,
      imageUrl: cat.imageUrl,
      description: cat.description,
      createdAt: cat.createdAt,
      parentId: cat.parentId},
    productCount: cat._count.products,
    children: cat.children.map(child => ({
      category: {
        id: child.id,
        title: child.title,
        slug: child.slug,
        imageUrl: child.imageUrl,
        description: child.description,
        createdAt: child.createdAt,
        parentId: child.parentId},
      productCount: child._count.products}))}));
}