moved variant sorting from service to the repository

This commit is contained in:
pKorsholm
2021-09-08 14:14:28 +02:00
parent ecad9db924
commit 6bd0d4458c
2 changed files with 26 additions and 16 deletions
+26 -6
View File
@@ -19,7 +19,7 @@ export class ProductRepository extends Repository<Product> {
}
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<Product> {
}
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")
-10
View File
@@ -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) {