Sfoglia il codice sorgente

refactor(core): Re-work caching on collection resolver

Will Nahmens 1 settimana fa
parent
commit
10cf314bc9

+ 3 - 19
packages/core/src/api/resolvers/entity/collection-entity.resolver.ts

@@ -74,31 +74,15 @@ export class CollectionEntityResolver {
         // Check if count was pre-loaded in findAll
         const cachedCount = (collection as Collection & { __productVariantCount: number })
             .__productVariantCount;
-        // Only treat as count-only when explicit flag is provided
-        const isCountOnlyRequest = (options as any)?.countOnly === true;
 
-        if (isCountOnlyRequest && cachedCount !== undefined) {
-            // Return cached count without querying for explicit count-only requests
-            return {
-                items: [],
-                totalItems: cachedCount,
-            };
-        }
-
-        // Fetch items normally (cachedCount will optimize the totalItems query if available)
-        const result = await this.productVariantService.getVariantsByCollectionId(
+        // Fetch items, passing cached count to avoid redundant count query when available
+        return this.productVariantService.getVariantsByCollectionId(
             ctx,
             collection.id,
             options,
             relations,
+            cachedCount,
         );
-
-        // Use cached count to avoid extra query if available and no filters applied
-        if (cachedCount !== undefined && !options?.filter) {
-            result.totalItems = cachedCount;
-        }
-
-        return result;
     }
 
     @ResolveField()

+ 12 - 0
packages/core/src/service/services/product-variant.service.ts

@@ -211,6 +211,7 @@ export class ProductVariantService {
         collectionId: ID,
         options: ListQueryOptions<ProductVariant>,
         relations: RelationPaths<ProductVariant> = [],
+        cachedTotalItems?: number,
     ): Promise<PaginatedList<Translated<ProductVariant>>> {
         const qb = this.listQueryBuilder
             .build(ProductVariant, options, {
@@ -228,6 +229,17 @@ export class ProductVariantService {
             qb.andWhere('product.enabled = :enabled', { enabled: true });
         }
 
+        // If a cached count is provided and no filters are applied, use it to avoid a duplicate count query
+        if (cachedTotalItems !== undefined && !options?.filter) {
+            return qb.getMany().then(async variants => {
+                const items = await this.applyPricesAndTranslateVariants(ctx, variants);
+                return {
+                    items,
+                    totalItems: cachedTotalItems,
+                };
+            });
+        }
+
         return qb.getManyAndCount().then(async ([variants, totalItems]) => {
             const items = await this.applyPricesAndTranslateVariants(ctx, variants);
             return {