From 6bd0d4458cdf12fabc00187afb1e0504b883758c Mon Sep 17 00:00:00 2001 From: pKorsholm Date: Wed, 8 Sep 2021 14:14:28 +0200 Subject: [PATCH] moved variant sorting from service to the repository --- packages/medusa/src/repositories/product.ts | 32 +++++++++++++++++---- packages/medusa/src/services/product.js | 10 ------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/packages/medusa/src/repositories/product.ts b/packages/medusa/src/repositories/product.ts index dd1dc83c8f..f565c86751 100644 --- a/packages/medusa/src/repositories/product.ts +++ b/packages/medusa/src/repositories/product.ts @@ -19,7 +19,7 @@ export class ProductRepository extends Repository { } const entitiesIds = entities.map(({ id }) => id) - const groupedRelations = {} + const groupedRelations : { [toplevel: string]: string[]} = {} for (const rel of relations) { const [topLevel] = rel.split(".") if (groupedRelations[topLevel]) { @@ -30,13 +30,33 @@ export class ProductRepository extends Repository { } const entitiesIdsWithRelations = await Promise.all( - Object.entries(groupedRelations).map(([_, rels]) => { - return this.findByIds(entitiesIds, { - select: ["id"], - relations: rels as string[], - }) + Object.entries(groupedRelations).map(([toplevel, rels]) => { + let querybuilder = this.createQueryBuilder("products") + + if (toplevel === "variants") { + querybuilder = querybuilder.leftJoinAndSelect(`products.${toplevel}`, toplevel, "variants.deleted_at IS NULL") + .orderBy({ + "variants.variant_rank": "ASC", + }) + } else { + querybuilder = querybuilder.leftJoinAndSelect(`products.${toplevel}`, toplevel) + } + + for(const rel of rels) { + const [_, rest] = rel.split(".") + if (!rest) { + continue + } + // Regex matches all '.' except the rightmost + querybuilder = querybuilder.leftJoinAndSelect(rel.replace(/\.(?=[^.]*\.)/g,"__"), rel.replace(".", "__")) + } + + return querybuilder + .where("products.deleted_at IS NULL AND products.id IN (:...entitiesIds)", { entitiesIds }) + .getMany(); }) ).then(flatten) + const entitiesAndRelations = entitiesIdsWithRelations.concat(entities) const entitiesAndRelationsById = groupBy(entitiesAndRelations, "id") diff --git a/packages/medusa/src/services/product.js b/packages/medusa/src/services/product.js index dc020b45c7..45b7375af4 100644 --- a/packages/medusa/src/services/product.js +++ b/packages/medusa/src/services/product.js @@ -185,12 +185,6 @@ class ProductService extends BaseService { ) } - if (product.variants) { - product.variants.sort( - (variant1, variant2) => variant1.variant_rank - variant2.variant_rank - ) - } - return product } @@ -299,10 +293,6 @@ class ProductService extends BaseService { rest.discountable = false } - if (rest.variants) - for (const [i, variant] of rest.variants.entries()) - variant.variant_rank = i - let product = productRepo.create(rest) if (images && images.length) {