Skip to content

Commit

Permalink
fix(medusa): Sales Channel migration script (#2521)
Browse files Browse the repository at this point in the history
  • Loading branch information
olivermrbl authored Nov 2, 2022
1 parent 144ce0e commit 684f68c
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions packages/medusa/src/scripts/sales-channels-migration.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import dotenv from "dotenv"
import { createConnection } from "typeorm"
import Logger from "../loaders/logger"
import { Product } from "../models/product";
import { Store } from "../models/store";
import { Product } from "../models/product"
import { Store } from "../models/store"

dotenv.config()

Expand All @@ -23,24 +23,29 @@ const migrate = async function ({ typeormConfig }): Promise<void> {
const BATCH_SIZE = 1000

await connection.transaction(async (manager) => {
const store = await manager
const store: Store | undefined = await manager
.createQueryBuilder()
.from(Store, "store")
.select("store.default_sales_channel_id")
.getOne() as Store
.getRawOne()

if (!store.default_sales_channel_id) {
Logger.error(`The default sales channel does not exists yet. Run your project and then re run the migration.`)
if (!store?.default_sales_channel_id) {
Logger.error(
`The default sales channel does not exists yet. Run your project and then re run the migration.`
)
process.exit(1)
return
}

let shouldContinue = true
while (shouldContinue) {
const products = await manager
.createQueryBuilder()
.from(Product, "product")
.leftJoin("product_sales_channel", "product_sc", "product_sc.product_id = product.id")
.leftJoin(
"product_sales_channel",
"product_sc",
"product_sc.product_id = product.id"
)
.andWhere("product_sc.product_id IS NULL")
.select("product.id as id")
.distinct(true)
Expand All @@ -54,8 +59,8 @@ const migrate = async function ({ typeormConfig }): Promise<void> {
.into("product_sales_channel")
.values(
products.map((product) => ({
product_id: product.id,
sales_channel_id: store.default_sales_channel_id,
product_id: product.id
}))
)
.orIgnore()
Expand All @@ -65,7 +70,11 @@ const migrate = async function ({ typeormConfig }): Promise<void> {
const danglingProductCount = await manager
.createQueryBuilder()
.from(Product, "product")
.leftJoin("product_sales_channel", "product_sc", "product_sc.product_id = product.id")
.leftJoin(
"product_sales_channel",
"product_sc",
"product_sc.product_id = product.id"
)
.andWhere("product_sc.product_id IS NULL")
.getCount()
shouldContinue = !!danglingProductCount
Expand Down

0 comments on commit 684f68c

Please sign in to comment.