Skip to content

Commit

Permalink
chore(medusa): migrate SalesChannel / ProductCategory repository (med…
Browse files Browse the repository at this point in the history
…usajs#3728)

* chore: Migrate sales channel repository

* chore: migrated product categories

* chore: remove alias + rename changset

* chore(medusa): Cleanup publishable api key sales channel repo

* rm comment

---------

Co-authored-by: adrien2p <adrien.deperetti@gmail.com>
  • Loading branch information
riqwan and adrien2p authored Apr 5, 2023
1 parent 30ee10f commit 713d85a
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 67 deletions.
5 changes: 5 additions & 0 deletions .changeset/eight-monkeys-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@medusajs/medusa": patch
---

chore(medusa): migrate SalesChannel / ProductCategory repository
44 changes: 22 additions & 22 deletions packages/medusa/src/repositories/product-category.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,22 +44,22 @@ export const ProductCategoryRepository = dataSource
const options_ = { ...options }
options_.where = options_.where as FindOptionsWhere<ProductCategory>

const legacySelect = buildLegacyFieldsListFrom(options_.select)
const legacyRelations = buildLegacyFieldsListFrom(options_.relations)
const columnsSelected = buildLegacyFieldsListFrom(options_.select)
const relationsSelected = buildLegacyFieldsListFrom(options_.relations)

const selectStatements = (relationName: string): string[] => {
const fetchSelectColumns = (relationName: string): string[] => {
const modelColumns = this.metadata.ownColumns.map(
(column) => column.propertyName
)
const selectColumns = legacySelect.length ? legacySelect : modelColumns
const selectColumns = columnsSelected.length ? columnsSelected : modelColumns

return selectColumns.map((column) => {
return `${relationName}.${column}`
})
}

const queryBuilder = this.createQueryBuilder(entityName)
.select(selectStatements(entityName))
.select(fetchSelectColumns(entityName))
.skip(options_.skip)
.take(options_.take)
.addOrderBy(`${entityName}.rank`, "ASC")
Expand All @@ -69,18 +69,18 @@ export const ProductCategoryRepository = dataSource
delete options_.where?.name
delete options_.where?.handle

queryBuilder.where(
new Brackets((bracket) => {
bracket
.where({ name: ILike(`%${q}%`) })
.orWhere({ handle: ILike(`%${q}%`) })
})
)
options_.where = [{
...options_.where,
name: ILike(`%${q}%`)
}, {
...options_.where,
handle: ILike(`%${q}%`)
}]
}

queryBuilder.andWhere(options_.where)
queryBuilder.where(options_.where)

const includedTreeRelations: string[] = legacyRelations.filter((rel) =>
const includedTreeRelations: string[] = relationsSelected.filter((rel) =>
ProductCategory.treeRelations.includes(rel)
)

Expand All @@ -96,12 +96,12 @@ export const ProductCategoryRepository = dataSource
treeWhere,
treeScope
)
.addSelect(selectStatements(treeRelation))
.addSelect(fetchSelectColumns(treeRelation))
.addOrderBy(`${treeRelation}.rank`, "ASC")
.addOrderBy(`${treeRelation}.handle`, "ASC")
})

const nonTreeRelations: string[] = legacyRelations.filter(
const nonTreeRelations: string[] = relationsSelected.filter(
(rel) => !ProductCategory.treeRelations.includes(rel)
)

Expand All @@ -128,15 +128,15 @@ export const ProductCategoryRepository = dataSource
productCategoryId: string,
productIds: string[]
): Promise<void> {
const valuesToInsert = productIds.map((id) => ({
product_category_id: productCategoryId,
product_id: id,
}))

await this.createQueryBuilder()
.insert()
.into(ProductCategory.productCategoryProductJoinTable)
.values(
productIds.map((id) => ({
product_category_id: productCategoryId,
product_id: id,
}))
)
.values(valuesToInsert)
.orIgnore()
.execute()
},
Expand Down
3 changes: 1 addition & 2 deletions packages/medusa/src/repositories/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import { dataSource } from "../loaders/database"
import { ProductFilterOptions } from "../types/product"
import {
buildLegacyFieldsListFrom,
isObject,
fetchCategoryDescendantsIds,
isObject,
} from "../utils"

export const ProductRepository = dataSource.getRepository(Product).extend({
Expand Down Expand Up @@ -123,7 +123,6 @@ export const ProductRepository = dataSource.getRepository(Product).extend({
delete options_.where.include_category_children
delete options_.where.categories

// TODO: move back to the service layer
if (q) {
options_.relations = options_.relations ?? {}
options_.relations.variants = options_.relations.variants ?? true
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { Brackets, In } from "typeorm"

import { PublishableApiKeySalesChannel, SalesChannel } from "../models"
import { dataSource } from "../loaders/database"
import SalesChannelRepository from "./sales-channel"

const publishableApiKeySalesChannelAlias = "PublishableKeySalesChannel"

export const PublishableApiKeySalesChannelRepository = dataSource
.getRepository(PublishableApiKeySalesChannel)
Expand All @@ -16,35 +19,38 @@ export const PublishableApiKeySalesChannelRepository = dataSource
publishableApiKeyId: string,
config?: { q?: string }
): Promise<SalesChannel[]> {
const query = this.createQueryBuilder("PublishableKeySalesChannel")
.select("PublishableKeySalesChannel.sales_channel_id")
.innerJoinAndMapOne(
"PublishableKeySalesChannel.sales_channel_id",
SalesChannel,
"SalesChannel",
"PublishableKeySalesChannel.sales_channel_id = SalesChannel.id"
)
const salesChannelAlias = "sales_channel"

const queryBuilder = this.createQueryBuilder(
publishableApiKeySalesChannelAlias
)
.select(`${salesChannelAlias}.*`)
.from(SalesChannel, salesChannelAlias)
.where(
"PublishableKeySalesChannel.publishable_key_id = :publishableApiKeyId",
`${publishableApiKeySalesChannelAlias}.publishable_key_id = :publishableApiKeyId`,
{
publishableApiKeyId,
}
)
.andWhere(
`${publishableApiKeySalesChannelAlias}.sales_channel_id = ${salesChannelAlias}.id`
)

if (config?.q) {
query.andWhere(
queryBuilder.andWhere(
new Brackets((qb) => {
qb.where(`SalesChannel.description ILIKE :q`, {
qb.where(`${salesChannelAlias}.description ILIKE :q`, {
q: `%${config.q}%`,
}).orWhere(`${salesChannelAlias}.name ILIKE :q`, {
q: `%${config.q}%`,
}).orWhere(`SalesChannel.name ILIKE :q`, { q: `%${config.q}%` })
})
})
)
}

const records = await query.getMany()

return records.map(
(record) => record.sales_channel_id as unknown as SalesChannel
const records = await queryBuilder.getRawMany()
return records.map((salesChannel: SalesChannel) =>
SalesChannelRepository.create(salesChannel)
)
},

Expand All @@ -60,7 +66,7 @@ export const PublishableApiKeySalesChannelRepository = dataSource
): Promise<void> {
await this.createQueryBuilder()
.insert()
.into("publishable_api_key_sales_channel")
.into(PublishableApiKeySalesChannel)
.values(
salesChannelIds.map((id) => ({
sales_channel_id: id,
Expand All @@ -83,7 +89,7 @@ export const PublishableApiKeySalesChannelRepository = dataSource
): Promise<void> {
await this.createQueryBuilder()
.delete()
.from("publishable_api_key_sales_channel")
.from(PublishableApiKeySalesChannel)
.where({
sales_channel_id: In(salesChannelIds),
publishable_key_id: publishableApiKeyId,
Expand Down
59 changes: 34 additions & 25 deletions packages/medusa/src/repositories/sales-channel.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { Brackets, DeleteResult, FindOptionsWhere, In } from "typeorm"
import { Brackets, DeleteResult, FindOptionsWhere, In, ILike } from "typeorm"
import { SalesChannel } from "../models"
import { ExtendedFindConfig } from "../types/common"
import { dataSource } from "../loaders/database"

const productSalesChannelTable = "product_sales_channel"

export const SalesChannelRepository = dataSource
.getRepository(SalesChannel)
.extend({
Expand All @@ -13,25 +15,29 @@ export const SalesChannelRepository = dataSource
}
): Promise<[SalesChannel[], number]> {
const options_ = { ...options }
options_.where = options_.where as FindOptionsWhere<SalesChannel>

options_.where = options_.where as FindOptionsWhere<SalesChannel>
delete options_?.where?.name
delete options_?.where?.description

let qb = this.createQueryBuilder("sales_channel")
options_.where = [
{
...options_.where,
name: ILike(`%${q}%`),
},
{
...options_.where,
description: ILike(`%${q}%`),
},
]

let qb = this.createQueryBuilder()
.select()
.where(options_.where)
.andWhere(
new Brackets((qb) => {
qb.where(`sales_channel.description ILIKE :q`, {
q: `%${q}%`,
}).orWhere(`sales_channel.name ILIKE :q`, { q: `%${q}%` })
})
)
.skip(options.skip)
.take(options.take)
.skip(options_.skip)
.take(options_.take)

if (options.withDeleted) {
if (options_.withDeleted) {
qb = qb.withDeleted()
}

Expand All @@ -42,31 +48,34 @@ export const SalesChannelRepository = dataSource
salesChannelId: string,
productIds: string[]
): Promise<DeleteResult> {
const whereOptions = {
sales_channel_id: salesChannelId,
product_id: In(productIds),
}

return await this.createQueryBuilder()
.delete()
.from("product_sales_channel")
.where({
sales_channel_id: salesChannelId,
product_id: In(productIds),
})
.from(productSalesChannelTable)
.where(whereOptions)
.execute()
},

async addProducts(
salesChannelId: string,
productIds: string[]
): Promise<void> {
const valuesToInsert = productIds.map((id) => ({
sales_channel_id: salesChannelId,
product_id: id,
}))

await this.createQueryBuilder()
.insert()
.into("product_sales_channel")
.values(
productIds.map((id) => ({
sales_channel_id: salesChannelId,
product_id: id,
}))
)
.into(productSalesChannelTable)
.values(valuesToInsert)
.orIgnore()
.execute()
},
})

export default SalesChannelRepository

0 comments on commit 713d85a

Please sign in to comment.