From 684f68ce122dcc82fac4f2f1183038b565795dd8 Mon Sep 17 00:00:00 2001 From: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com> Date: Wed, 2 Nov 2022 13:37:46 +0100 Subject: [PATCH] fix(medusa): Sales Channel migration script (#2521) --- .../src/scripts/sales-channels-migration.ts | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/packages/medusa/src/scripts/sales-channels-migration.ts b/packages/medusa/src/scripts/sales-channels-migration.ts index a317923667..f74660be1c 100644 --- a/packages/medusa/src/scripts/sales-channels-migration.ts +++ b/packages/medusa/src/scripts/sales-channels-migration.ts @@ -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 { 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 { 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 { .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 { 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