fix(medusa): Sales Channel migration script (#2521)

This commit is contained in:
Oliver Windall Juhl
2022-11-02 13:37:46 +01:00
committed by GitHub
parent 144ce0e42c
commit 684f68ce12

View File

@@ -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()
@@ -23,16 +23,17 @@ 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
@@ -40,7 +41,11 @@ const migrate = async function ({ typeormConfig }): Promise<void> {
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)
@@ -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()
@@ -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