feat(utils): Introduce promiseAll util (#5543)

This commit is contained in:
Adrien de Peretti authored and GitHub committed 2023-11-08 08:48:48 +01:00
1 parent e4ce2f4e07
commit f90ba02087
99 files changed
+440 -273

No files matched your search

+10
View File
@@ -0,0 +1,10 @@
---
"@medusajs/medusa": patch
"@medusajs/inventory": patch
"medusa-fulfillment-webshipper": patch
"medusa-plugin-brightpearl": patch
"medusa-plugin-contentful": patch
"medusa-source-shopify": patch
---
feat(utils): Introduce promiseAll util
+2 -1
View File
@@ -22,6 +22,7 @@ import {
InjectEntityManager, InjectEntityManager,
MedusaContext, MedusaContext,
MedusaError, MedusaError,
promiseAll,
} from "@medusajs/utils" } from "@medusajs/utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { joinerConfig } from "../joiner-config" import { joinerConfig } from "../joiner-config"
@@ -473,7 +474,7 @@ export default class InventoryService implements IInventoryService {
return acc return acc
}, new Map()) }, new Map())
return await Promise.all( return await promiseAll(
updates.map(async (update) => { updates.map(async (update) => {
const levelId = levelMap const levelId = levelMap
.get(update.inventory_item_id) .get(update.inventory_item_id)
@@ -11,6 +11,7 @@ import {
isDefined, isDefined,
MedusaContext, MedusaContext,
MedusaError, MedusaError,
promiseAll,
} from "@medusajs/utils" } from "@medusajs/utils"
import { EntityManager, FindManyOptions, In } from "typeorm" import { EntityManager, FindManyOptions, In } from "typeorm"
import { InventoryLevelService } from "." import { InventoryLevelService } from "."
@@ -150,7 +151,7 @@ export default class ReservationItemService {
})) }))
) )
const [newReservationItems] = await Promise.all([ const [newReservationItems] = await promiseAll([
reservationItemRepository.save(reservationItems), reservationItemRepository.save(reservationItems),
...data.map( ...data.map(
async (data) => async (data) =>
@@ -228,7 +229,7 @@ export default class ReservationItemService {
ops.push(itemRepository.save(item)) ops.push(itemRepository.save(item))
await Promise.all(ops) await promiseAll(ops)
await this.eventBusService_?.emit?.(ReservationItemService.Events.UPDATED, { await this.eventBusService_?.emit?.(ReservationItemService.Events.UPDATED, {
id: mergedItem.id, id: mergedItem.id,
@@ -273,7 +274,7 @@ export default class ReservationItemService {
) )
} }
await Promise.all(ops) await promiseAll(ops)
await this.eventBusService_?.emit?.(ReservationItemService.Events.DELETED, { await this.eventBusService_?.emit?.(ReservationItemService.Events.DELETED, {
line_item_id: lineItemId, line_item_id: lineItemId,
@@ -330,7 +331,7 @@ export default class ReservationItemService {
promises.push(itemRepository.softRemove(items)) promises.push(itemRepository.softRemove(items))
await Promise.all(promises) await promiseAll(promises)
await this.eventBusService_?.emit?.(ReservationItemService.Events.DELETED, { await this.eventBusService_?.emit?.(ReservationItemService.Events.DELETED, {
ids: reservationItemId, ids: reservationItemId,
@@ -35,6 +35,7 @@
"medusa-interfaces": "^1.3.7" "medusa-interfaces": "^1.3.7"
}, },
"dependencies": { "dependencies": {
"@medusajs/utils": "workspace:^",
"axios": "^0.20.0", "axios": "^0.20.0",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"cors": "^2.8.5", "cors": "^2.8.5",
@@ -1,6 +1,7 @@
import { humanizeAmount } from "medusa-core-utils" import { humanizeAmount } from "medusa-core-utils"
import Webshipper from "../utils/webshipper" import Webshipper from "../utils/webshipper"
import { AbstractFulfillmentService } from "@medusajs/medusa" import { AbstractFulfillmentService } from "@medusajs/medusa"
import { promiseAll } from "@medusajs/utils"
class WebshipperFulfillmentService extends AbstractFulfillmentService { class WebshipperFulfillmentService extends AbstractFulfillmentService {
static identifier = "webshipper" static identifier = "webshipper"
@@ -242,7 +243,7 @@ class WebshipperFulfillmentService extends AbstractFulfillmentService {
width: 15, width: 15,
length: 15, length: 15,
}, },
customs_lines: await Promise.all( customs_lines: await promiseAll(
returnOrder.items.map(async ({ item, quantity }) => { returnOrder.items.map(async ({ item, quantity }) => {
const customLine = await this.buildWebshipperItem( const customLine = await this.buildWebshipperItem(
item, item,
@@ -405,7 +406,7 @@ class WebshipperFulfillmentService extends AbstractFulfillmentService {
status: "pending", status: "pending",
ext_ref, ext_ref,
visible_ref, visible_ref,
order_lines: await Promise.all( order_lines: await promiseAll(
fulfillmentItems.map(async (item) => { fulfillmentItems.map(async (item) => {
const orderLine = await this.buildWebshipperItem( const orderLine = await this.buildWebshipperItem(
item, item,
@@ -41,6 +41,7 @@
"medusa-interfaces": "^1.3.7" "medusa-interfaces": "^1.3.7"
}, },
"dependencies": { "dependencies": {
"@medusajs/utils": "workspace:^",
"axios": "^0.19.2", "axios": "^0.19.2",
"axios-rate-limit": "^1.2.1", "axios-rate-limit": "^1.2.1",
"express": "^4.17.1", "express": "^4.17.1",
@@ -1,8 +1,9 @@
import { MedusaError, humanizeAmount } from "medusa-core-utils" import { humanizeAmount, MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces" import { BaseService } from "medusa-interfaces"
import Brightpearl from "../utils/brightpearl" import Brightpearl from "../utils/brightpearl"
import { updateInventoryAndReservations } from "@medusajs/medusa" import { updateInventoryAndReservations } from "@medusajs/medusa"
import { promiseAll } from "@medusajs/utils"
class BrightpearlService extends BaseService { class BrightpearlService extends BaseService {
constructor( constructor(
@@ -117,7 +118,7 @@ class BrightpearlService extends BaseService {
httpMethod: "POST", httpMethod: "POST",
uriTemplate: `${this.options.backend_url}/brightpearl/inventory-update`, uriTemplate: `${this.options.backend_url}/brightpearl/inventory-update`,
bodyTemplate: bodyTemplate:
"{\"account\": \"${account-code}\", \"lifecycle_event\": \"${lifecycle-event}\", \"resource_type\": \"${resource-type}\", \"id\": \"${resource-id}\" }", '{"account": "${account-code}", "lifecycle_event": "${lifecycle-event}", "resource_type": "${resource-type}", "id": "${resource-id}" }',
contentType: "application/json", contentType: "application/json",
idSetAccepted: false, idSetAccepted: false,
}, },
@@ -195,7 +196,7 @@ class BrightpearlService extends BaseService {
variants.filter((variant) => !!variant.sku).map((v) => [v.sku, v]) variants.filter((variant) => !!variant.sku).map((v) => [v.sku, v])
) )
const variantUpdates = await Promise.all( const variantUpdates = await promiseAll(
bpProducts.map(async (bpProduct) => { bpProducts.map(async (bpProduct) => {
const { SKU: sku, productId } = bpProduct const { SKU: sku, productId } = bpProduct
@@ -278,7 +279,7 @@ class BrightpearlService extends BaseService {
this.logger_.info("Synchronizing inventory levels") this.logger_.info("Synchronizing inventory levels")
await Promise.all( await promiseAll(
bpProducts.map(async (bpProduct, index) => { bpProducts.map(async (bpProduct, index) => {
if (index % 100 === 0) { if (index % 100 === 0) {
this.logger_.info( this.logger_.info(
@@ -291,7 +292,7 @@ class BrightpearlService extends BaseService {
const productAvailability = availabilities[productId] const productAvailability = availabilities[productId]
if (productAvailability) { if (productAvailability) {
await Promise.all( await promiseAll(
locations.map(async (location) => { locations.map(async (location) => {
const warehouseData = const warehouseData =
productAvailability.warehouses[ productAvailability.warehouses[
@@ -355,9 +356,7 @@ class BrightpearlService extends BaseService {
} }
const externallyReservedQuantityAdjustment = const externallyReservedQuantityAdjustment =
bpinStock - bpinStock - bpOnHand - inventoryLevel.reserved_quantity
bpOnHand -
inventoryLevel.reserved_quantity
if (externallyReservedQuantityAdjustment === 0) { if (externallyReservedQuantityAdjustment === 0) {
return return
@@ -455,7 +454,7 @@ class BrightpearlService extends BaseService {
productAvailability.warehouses[`${location.metadata.bp_id}`] productAvailability.warehouses[`${location.metadata.bp_id}`]
) )
await Promise.all( await promiseAll(
locations.map(async (location) => { locations.map(async (location) => {
// TODO: Assuming we have a 1 to 1 mapping of inventory items // TODO: Assuming we have a 1 to 1 mapping of inventory items
const inventoryLevel = inventoryMap[location.id][0] const inventoryLevel = inventoryMap[location.id][0]
@@ -703,7 +702,7 @@ class BrightpearlService extends BaseService {
order.metadata.brightpearl_sales_order_id order.metadata.brightpearl_sales_order_id
) )
const rows = await Promise.all( const rows = await promiseAll(
lineItems.map(async (item) => { lineItems.map(async (item) => {
const reservations = lineItemReservationsMap.get(item.id) const reservations = lineItemReservationsMap.get(item.id)
const variant = variantMap.get(item.variant_id) const variant = variantMap.get(item.variant_id)
@@ -1337,7 +1336,7 @@ class BrightpearlService extends BaseService {
async gatherRowsFromOrderIds(ids) { async gatherRowsFromOrderIds(ids) {
const client = await this.getClient() const client = await this.getClient()
const orders = await Promise.all(ids.map((i) => client.orders.retrieve(i))) const orders = await promiseAll(ids.map((i) => client.orders.retrieve(i)))
let rows = [] let rows = []
for (const o of orders) { for (const o of orders) {
@@ -1477,7 +1476,7 @@ class BrightpearlService extends BaseService {
) { ) {
const { region } = fromOrder const { region } = fromOrder
const lines = await Promise.all( const lines = await promiseAll(
fromOrder.items.map(async (item) => { fromOrder.items.map(async (item) => {
const bpProduct = await this.retrieveProductBySKU(item.variant.sku) const bpProduct = await this.retrieveProductBySKU(item.variant.sku)
@@ -37,6 +37,7 @@
}, },
"dependencies": { "dependencies": {
"@babel/plugin-transform-classes": "^7.9.5", "@babel/plugin-transform-classes": "^7.9.5",
"@medusajs/utils": "workspace:^",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"contentful-management": "^5.27.1", "contentful-management": "^5.27.1",
"express": "^4.17.1", "express": "^4.17.1",
@@ -1,6 +1,7 @@
import { BaseService } from "medusa-interfaces" import { BaseService } from "medusa-interfaces"
import _ from "lodash" import _ from "lodash"
import { createClient } from "contentful-management" import { createClient } from "contentful-management"
import { promiseAll } from "@medusajs/utils"
const IGNORE_THRESHOLD = 2 // seconds const IGNORE_THRESHOLD = 2 // seconds
@@ -63,7 +64,7 @@ class ContentfulService extends BaseService {
} }
async getVariantEntries_(variants, config = { publish: false }) { async getVariantEntries_(variants, config = { publish: false }) {
const contentfulVariants = await Promise.all( const contentfulVariants = await promiseAll(
variants.map(async (variant) => { variants.map(async (variant) => {
let updated = await this.updateProductVariantInContentful(variant) let updated = await this.updateProductVariantInContentful(variant)
if (config.publish) { if (config.publish) {
@@ -21,6 +21,7 @@
}, },
"dependencies": { "dependencies": {
"@babel/plugin-transform-classes": "^7.15.4", "@babel/plugin-transform-classes": "^7.15.4",
"@medusajs/utils": "workspace:^",
"@shopify/shopify-api": "^1.4.1", "@shopify/shopify-api": "^1.4.1",
"axios": "^0.21.4", "axios": "^0.21.4",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
@@ -1,5 +1,6 @@
import { BaseService } from "medusa-interfaces" import { BaseService } from "medusa-interfaces"
import { INCLUDE_PRESENTMENT_PRICES } from "../utils/const" import { INCLUDE_PRESENTMENT_PRICES } from "../utils/const"
import { promiseAll } from "@medusajs/utils"
class ShopifyService extends BaseService { class ShopifyService extends BaseService {
constructor( constructor(
@@ -83,11 +84,10 @@ class ShopifyService extends BaseService {
updatedSinceQuery updatedSinceQuery
) )
const resolvedProducts = await Promise.all( const productServiceTx = this.productService_.withTransaction(manager)
const resolvedProducts = await promiseAll(
products.map(async (product) => { products.map(async (product) => {
return await this.productService_ return await productServiceTx.create(product)
.withTransaction(manager)
.create(product)
}) })
) )
@@ -14,6 +14,7 @@ import { EntityManager } from "typeorm"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { Order } from "../../../../models" import { Order } from "../../../../models"
import { cleanResponseData } from "../../../../utils/clean-response-data" import { cleanResponseData } from "../../../../utils/clean-response-data"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [post] /admin/draft-orders/{id}/pay * @oas [post] /admin/draft-orders/{id}/pay
@@ -130,7 +131,7 @@ export const reserveQuantityForDraftOrder = async (
} }
) => { ) => {
const { productVariantInventoryService, locationId } = context const { productVariantInventoryService, locationId } = context
await Promise.all( await promiseAll(
order.items.map(async (item) => { order.items.map(async (item) => {
if (item.variant_id) { if (item.variant_id) {
const inventoryConfirmed = const inventoryConfirmed =
@@ -4,6 +4,7 @@ import {
InventoryItemDTO, InventoryItemDTO,
InventoryLevelDTO, InventoryLevelDTO,
} from "@medusajs/types" } from "@medusajs/types"
import { promiseAll } from "@medusajs/utils"
import { LevelWithAvailability, ResponseInventoryItem } from "../../variants" import { LevelWithAvailability, ResponseInventoryItem } from "../../variants"
export const buildLevelsByInventoryItemId = ( export const buildLevelsByInventoryItemId = (
@@ -35,7 +36,7 @@ export const getLevelsByInventoryItemId = async (
const [levels] = await inventoryService.listInventoryLevels(selector, {}) const [levels] = await inventoryService.listInventoryLevels(selector, {})
const levelsWithAvailability: LevelWithAvailability[] = await Promise.all( const levelsWithAvailability: LevelWithAvailability[] = await promiseAll(
levels.map(async (level) => { levels.map(async (level) => {
const availability = await inventoryService.retrieveAvailableQuantity( const availability = await inventoryService.retrieveAvailableQuantity(
level.inventory_item_id, level.inventory_item_id,
@@ -10,6 +10,7 @@ import { EntityManager } from "typeorm"
import { Fulfillment } from "../../../../models" import { Fulfillment } from "../../../../models"
import { FindParams } from "../../../../types/common" import { FindParams } from "../../../../types/common"
import { cleanResponseData } from "../../../../utils/clean-response-data" import { cleanResponseData } from "../../../../utils/clean-response-data"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [post] /admin/orders/{id}/fulfillments/{fulfillment_id}/cancel * @oas [post] /admin/orders/{id}/fulfillments/{fulfillment_id}/cancel
@@ -120,7 +121,7 @@ export const adjustInventoryForCancelledFulfillment = async (
} }
) => { ) => {
const { productVariantInventoryService } = context const { productVariantInventoryService } = context
await Promise.all( await promiseAll(
fulfillment.items.map(async ({ item, quantity }) => { fulfillment.items.map(async ({ item, quantity }) => {
if (item.variant_id) { if (item.variant_id) {
await productVariantInventoryService.adjustInventory( await productVariantInventoryService.adjustInventory(
@@ -19,6 +19,7 @@ import { optionalBooleanMapper } from "../../../../utils/validators/is-boolean"
import { Fulfillment, LineItem } from "../../../../models" import { Fulfillment, LineItem } from "../../../../models"
import { FindParams } from "../../../../types/common" import { FindParams } from "../../../../types/common"
import { cleanResponseData } from "../../../../utils/clean-response-data" import { cleanResponseData } from "../../../../utils/clean-response-data"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [post] /admin/orders/{id}/fulfillment * @oas [post] /admin/orders/{id}/fulfillment
@@ -167,7 +168,7 @@ export const updateInventoryAndReservations = async (
) => { ) => {
const { inventoryService, locationId } = context const { inventoryService, locationId } = context
await Promise.all( await promiseAll(
fulfillments.map(async ({ items }) => { fulfillments.map(async ({ items }) => {
await inventoryService.validateInventoryAtLocation( await inventoryService.validateInventoryAtLocation(
items.map(({ item, quantity }) => ({ ...item, quantity } as LineItem)), items.map(({ item, quantity }) => ({ ...item, quantity } as LineItem)),
@@ -176,9 +177,9 @@ export const updateInventoryAndReservations = async (
}) })
) )
await Promise.all( await promiseAll(
fulfillments.map(async ({ items }) => { fulfillments.map(async ({ items }) => {
await Promise.all( await promiseAll(
items.map(async ({ item, quantity }) => { items.map(async ({ item, quantity }) => {
if (!item.variant_id) { if (!item.variant_id) {
return return
@@ -1,5 +1,5 @@
import { IInventoryService, WorkflowTypes } from "@medusajs/types" import { IInventoryService, WorkflowTypes } from "@medusajs/types"
import { Workflows, createProducts } from "@medusajs/workflows" import { createProducts, Workflows } from "@medusajs/workflows"
import { import {
IsArray, IsArray,
IsBoolean, IsBoolean,
@@ -39,7 +39,7 @@ import {
} from "./transaction/create-product-variant" } from "./transaction/create-product-variant"
import { DistributedTransaction } from "@medusajs/orchestration" import { DistributedTransaction } from "@medusajs/orchestration"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { Type } from "class-transformer" import { Type } from "class-transformer"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import IsolateProductDomainFeatureFlag from "../../../../loaders/feature-flags/isolate-product-domain" import IsolateProductDomainFeatureFlag from "../../../../loaders/feature-flags/isolate-product-domain"
@@ -242,7 +242,7 @@ export default async (req, res) => {
) )
allVariantTransactions.push(varTransaction) allVariantTransactions.push(varTransaction)
} catch (e) { } catch (e) {
await Promise.all( await promiseAll(
allVariantTransactions.map(async (transaction) => { allVariantTransactions.map(async (transaction) => {
await revertVariantTransaction( await revertVariantTransaction(
transactionDependencies, transactionDependencies,
@@ -6,7 +6,7 @@ import {
} from "../../../../services" } from "../../../../services"
import IsolateProductDomainFeatureFlag from "../../../../loaders/feature-flags/isolate-product-domain" import IsolateProductDomainFeatureFlag from "../../../../loaders/feature-flags/isolate-product-domain"
import { MedusaError } from "@medusajs/utils" import { MedusaError, promiseAll } from "@medusajs/utils"
import { FindParams } from "../../../../types/common" import { FindParams } from "../../../../types/common"
import { defaultAdminProductRemoteQueryObject } from "./index" import { defaultAdminProductRemoteQueryObject } from "./index"
@@ -114,7 +114,7 @@ export default async (req, res) => {
) )
) )
} }
await Promise.all(decoratePromises) await promiseAll(decoratePromises)
res.json({ product }) res.json({ product })
} }
@@ -14,6 +14,7 @@ import { PricedProduct } from "../../../../types/pricing"
import { Product } from "../../../../models" import { Product } from "../../../../models"
import { Type } from "class-transformer" import { Type } from "class-transformer"
import { defaultAdminProductRemoteQueryObject } from "./index" import { defaultAdminProductRemoteQueryObject } from "./index"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /admin/products * @oas [get] /admin/products
@@ -377,7 +378,7 @@ async function listAndCountProductWithIsolatedProductModule(
// TODO implement later // TODO implement later
} }
await Promise.all(promises) await promiseAll(promises)
if (productIdsFilter.size > 0) { if (productIdsFilter.size > 0) {
filterableFields.id = Array.from(productIdsFilter) filterableFields.id = Array.from(productIdsFilter)
@@ -14,7 +14,7 @@ import {
import { CreateProductVariantInput } from "../../../../../types/product-variant" import { CreateProductVariantInput } from "../../../../../types/product-variant"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { MedusaError } from "@medusajs/utils" import { MedusaError, promiseAll } from "@medusajs/utils"
import { ProductVariant } from "../../../../../models" import { ProductVariant } from "../../../../../models"
import { ulid } from "ulid" import { ulid } from "ulid"
@@ -92,7 +92,7 @@ export const createVariantsTransaction = async (
async function createInventoryItems(variants: ProductVariant[] = []) { async function createInventoryItems(variants: ProductVariant[] = []) {
const context = { transactionManager: manager } const context = { transactionManager: manager }
return await Promise.all( return await promiseAll(
variants.map(async (variant) => { variants.map(async (variant) => {
if (!variant.manage_inventory) { if (!variant.manage_inventory) {
return return
@@ -126,7 +126,7 @@ export const createVariantsTransaction = async (
) { ) {
const context = { transactionManager: manager } const context = { transactionManager: manager }
return await Promise.all( return await promiseAll(
data.map(async ({ inventoryItem }) => { data.map(async ({ inventoryItem }) => {
return await inventoryService!.deleteInventoryItem( return await inventoryService!.deleteInventoryItem(
inventoryItem.id, inventoryItem.id,
@@ -142,7 +142,7 @@ export const createVariantsTransaction = async (
inventoryItem: InventoryItemDTO inventoryItem: InventoryItemDTO
}[] }[]
) { ) {
return await Promise.all( return await promiseAll(
data data
.filter((d) => d) .filter((d) => d)
.map(async ({ variant, inventoryItem }) => { .map(async ({ variant, inventoryItem }) => {
@@ -1,6 +1,6 @@
import { DistributedTransaction } from "@medusajs/orchestration" import { DistributedTransaction } from "@medusajs/orchestration"
import { FlagRouter, MedusaError } from "@medusajs/utils" import { FlagRouter, MedusaError, promiseAll } from "@medusajs/utils"
import { Workflows, updateProducts } from "@medusajs/workflows" import { updateProducts, Workflows } from "@medusajs/workflows"
import { Type } from "class-transformer" import { Type } from "class-transformer"
import { import {
IsArray, IsArray,
@@ -272,7 +272,7 @@ export default async (req, res) => {
) )
allVariantTransactions.push(varTransaction) allVariantTransactions.push(varTransaction)
} catch (e) { } catch (e) {
await Promise.all( await promiseAll(
allVariantTransactions.map(async (transaction) => { allVariantTransactions.map(async (transaction) => {
await revertVariantTransaction( await revertVariantTransaction(
transactionDependencies, transactionDependencies,
@@ -1,8 +1,8 @@
import { import {
DateComparisonOperator, DateComparisonOperator,
extendedFindParamsMixin,
NumericalComparisonOperator, NumericalComparisonOperator,
StringComparisonOperator, StringComparisonOperator,
extendedFindParamsMixin,
} from "../../../../types/common" } from "../../../../types/common"
import { IsArray, IsOptional, IsString, ValidateNested } from "class-validator" import { IsArray, IsOptional, IsString, ValidateNested } from "class-validator"
import { Request, Response } from "express" import { Request, Response } from "express"
@@ -14,6 +14,7 @@ import { LineItemService } from "../../../../services"
import { Type } from "class-transformer" import { Type } from "class-transformer"
import { joinInventoryItems } from "./utils/join-inventory-items" import { joinInventoryItems } from "./utils/join-inventory-items"
import { joinLineItems } from "./utils/join-line-items" import { joinLineItems } from "./utils/join-line-items"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /admin/reservations * @oas [get] /admin/reservations
@@ -198,7 +199,7 @@ export default async (req: Request, res: Response) => {
promises.push(joinLineItems(reservations, lineItemService)) promises.push(joinLineItems(reservations, lineItemService))
} }
await Promise.all(promises) await promiseAll(promises)
const { limit, offset } = req.validatedQuery const { limit, offset } = req.validatedQuery
@@ -1,4 +1,5 @@
import { IInventoryService, IStockLocationService } from "@medusajs/types" import { IInventoryService, IStockLocationService } from "@medusajs/types"
import { promiseAll } from "@medusajs/utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { SalesChannelLocationService } from "../../../../services" import { SalesChannelLocationService } from "../../../../services"
@@ -64,7 +65,7 @@ export default async (req, res) => {
await stockLocationService.delete(id) await stockLocationService.delete(id)
if (inventoryService) { if (inventoryService) {
await Promise.all([ await promiseAll([
inventoryService.deleteInventoryItemLevelByLocationId(id), inventoryService.deleteInventoryItemLevelByLocationId(id),
inventoryService.deleteReservationItemByLocationId(id), inventoryService.deleteReservationItemByLocationId(id),
]) ])
@@ -1,4 +1,5 @@
import { StockLocationDTO, StockLocationExpandedDTO } from "@medusajs/types" import { StockLocationDTO, StockLocationExpandedDTO } from "@medusajs/types"
import { promiseAll } from "@medusajs/utils"
import { import {
SalesChannelLocationService, SalesChannelLocationService,
SalesChannelService, SalesChannelService,
@@ -9,7 +10,7 @@ const joinSalesChannels = async (
channelLocationService: SalesChannelLocationService, channelLocationService: SalesChannelLocationService,
salesChannelService: SalesChannelService salesChannelService: SalesChannelService
): Promise<StockLocationExpandedDTO[]> => { ): Promise<StockLocationExpandedDTO[]> => {
return await Promise.all( return await promiseAll(
locations.map(async (location: StockLocationExpandedDTO) => { locations.map(async (location: StockLocationExpandedDTO) => {
const salesChannelIds = await channelLocationService.listSalesChannelIds( const salesChannelIds = await channelLocationService.listSalesChannelIds(
location.id location.id
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import fs from "fs" import fs from "fs"
import { IFileService } from "../../../../interfaces" import { IFileService } from "../../../../interfaces"
@@ -64,7 +65,7 @@ import { IFileService } from "../../../../interfaces"
export default async (req, res) => { export default async (req, res) => {
const fileService: IFileService = req.scope.resolve("fileService") const fileService: IFileService = req.scope.resolve("fileService")
const result = await Promise.all( const result = await promiseAll(
req.files.map(async (f) => { req.files.map(async (f) => {
return fileService.uploadProtected(f).then((result) => { return fileService.uploadProtected(f).then((result) => {
fs.unlinkSync(f.path) fs.unlinkSync(f.path)
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import fs from "fs" import fs from "fs"
/** /**
@@ -63,7 +64,7 @@ import fs from "fs"
export default async (req, res) => { export default async (req, res) => {
const fileService = req.scope.resolve("fileService") const fileService = req.scope.resolve("fileService")
const result = await Promise.all( const result = await promiseAll(
req.files.map(async (f) => { req.files.map(async (f) => {
return fileService.upload(f).then((result) => { return fileService.upload(f).then((result) => {
fs.unlinkSync(f.path) fs.unlinkSync(f.path)
@@ -11,6 +11,7 @@ import {
import ProductVariantService from "../../../../services/product-variant" import ProductVariantService from "../../../../services/product-variant"
import ProductVariantInventoryService from "../../../../services/product-variant-inventory" import ProductVariantInventoryService from "../../../../services/product-variant-inventory"
import { joinLevels } from "../inventory-items/utils/join-levels" import { joinLevels } from "../inventory-items/utils/join-levels"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /admin/variants/{id}/inventory * @oas [get] /admin/variants/{id}/inventory
@@ -92,7 +93,7 @@ export default async (req, res) => {
} }
const [rawChannels] = await channelService.listAndCount({}) const [rawChannels] = await channelService.listAndCount({})
const channels: SalesChannelDTO[] = await Promise.all( const channels: SalesChannelDTO[] = await promiseAll(
rawChannels.map(async (channel) => { rawChannels.map(async (channel) => {
const locationIds = await channelLocationService.listLocationIds( const locationIds = await channelLocationService.listLocationIds(
channel.id channel.id
@@ -112,7 +113,7 @@ export default async (req, res) => {
responseVariant.inventory = await joinLevels(inventory, [], inventoryService) responseVariant.inventory = await joinLevels(inventory, [], inventoryService)
if (inventory.length) { if (inventory.length) {
responseVariant.sales_channel_availability = await Promise.all( responseVariant.sales_channel_availability = await promiseAll(
channels.map(async (channel) => { channels.map(async (channel) => {
if (!channel.locations.length) { if (!channel.locations.length) {
return { return {
@@ -2,6 +2,7 @@ import { Customer } from "../../../.."
import CustomerService from "../../../../services/customer" import CustomerService from "../../../../services/customer"
import PaymentProviderService from "../../../../services/payment-provider" import PaymentProviderService from "../../../../services/payment-provider"
import { PaymentProvider } from "../../../../models" import { PaymentProvider } from "../../../../models"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /store/customers/me/payment-methods * @oas [get] /store/customers/me/payment-methods
@@ -68,7 +69,7 @@ export default async (req, res) => {
const paymentProviders: PaymentProvider[] = const paymentProviders: PaymentProvider[] =
await paymentProviderService.list() await paymentProviderService.list()
const methods = await Promise.all( const methods = await promiseAll(
paymentProviders.map(async (paymentProvider: PaymentProvider) => { paymentProviders.map(async (paymentProvider: PaymentProvider) => {
const provider = paymentProviderService.retrieveProvider( const provider = paymentProviderService.retrieveProvider(
paymentProvider.id paymentProvider.id
@@ -5,6 +5,7 @@ import {
OrderService, OrderService,
TokenService, TokenService,
} from "../../../../services" } from "../../../../services"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [post] /store/orders/customer/confirm * @oas [post] /store/orders/customer/confirm
@@ -96,7 +97,7 @@ export default async (req, res) => {
const orders = await orderService.list({ id: orderIds }) const orders = await orderService.list({ id: orderIds })
await Promise.all( await promiseAll(
orders.map(async (order) => { orders.map(async (order) => {
await orderSerivce await orderSerivce
.withTransaction(transactionManager) .withTransaction(transactionManager)
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import { IsNotEmpty, IsString } from "class-validator" import { IsNotEmpty, IsString } from "class-validator"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { CustomerService, OrderService } from "../../../../services" import { CustomerService, OrderService } from "../../../../services"
@@ -102,7 +103,7 @@ export default async (req, res) => {
{} {}
) )
await Promise.all( await promiseAll(
Object.entries(emailOrderMapping).map(async ([email, order_ids]) => { Object.entries(emailOrderMapping).map(async ([email, order_ids]) => {
const token = tokenService.signToken( const token = tokenService.signToken(
{ {
@@ -7,7 +7,7 @@ import {
RegionService, RegionService,
} from "../../../../services" } from "../../../../services"
import { MedusaError } from "@medusajs/utils" import { MedusaError, promiseAll } from "@medusajs/utils"
import IsolateProductDomain from "../../../../loaders/feature-flags/isolate-product-domain" import IsolateProductDomain from "../../../../loaders/feature-flags/isolate-product-domain"
import { PriceSelectionParams } from "../../../../types/price-selection" import { PriceSelectionParams } from "../../../../types/price-selection"
import { cleanResponseData } from "../../../../utils" import { cleanResponseData } from "../../../../utils"
@@ -156,7 +156,7 @@ export default async (req, res) => {
// We can run them concurrently as the new properties are assigned to the references // We can run them concurrently as the new properties are assigned to the references
// of the appropriate entity // of the appropriate entity
await Promise.all(decoratePromises) await promiseAll(decoratePromises)
res.json({ res.json({
product: cleanResponseData(decoratedProduct, req.allowedProperties || []), product: cleanResponseData(decoratedProduct, req.allowedProperties || []),
@@ -25,6 +25,7 @@ import { cleanResponseData } from "../../../../utils/clean-response-data"
import { defaultStoreCategoryScope } from "../product-categories" import { defaultStoreCategoryScope } from "../product-categories"
import { defaultStoreProductRemoteQueryObject } from "./index" import { defaultStoreProductRemoteQueryObject } from "./index"
import { optionalBooleanMapper } from "../../../../utils/validators/is-boolean" import { optionalBooleanMapper } from "../../../../utils/validators/is-boolean"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /store/products * @oas [get] /store/products
@@ -277,7 +278,7 @@ export default async (req, res) => {
) )
} }
const [[rawProducts, count], cart] = await Promise.all(promises) const [[rawProducts, count], cart] = await promiseAll(promises)
if (validated.cart_id) { if (validated.cart_id) {
regionId = cart.region_id regionId = cart.region_id
@@ -320,7 +321,7 @@ export default async (req, res) => {
// We can run them concurrently as the new properties are assigned to the references // We can run them concurrently as the new properties are assigned to the references
// of the appropriate entity // of the appropriate entity
await Promise.all(decoratePromises) await promiseAll(decoratePromises)
res.json({ res.json({
products: cleanResponseData(computedProducts, req.allowedProperties || []), products: cleanResponseData(computedProducts, req.allowedProperties || []),
@@ -9,6 +9,7 @@ import { IsOptional, IsString } from "class-validator"
import { PriceSelectionParams } from "../../../../types/price-selection" import { PriceSelectionParams } from "../../../../types/price-selection"
import { validator } from "../../../../utils/validator" import { validator } from "../../../../utils/validator"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /store/variants/{id} * @oas [get] /store/variants/{id}
@@ -122,7 +123,7 @@ export default async (req, res) => {
)) as any )) as any
) )
await Promise.all(decoratePromises) await promiseAll(decoratePromises)
res.json({ variant }) res.json({ variant })
} }
@@ -12,6 +12,7 @@ import { NumericalComparisonOperator } from "../../../../types/common"
import { PriceSelectionParams } from "../../../../types/price-selection" import { PriceSelectionParams } from "../../../../types/price-selection"
import { Type } from "class-transformer" import { Type } from "class-transformer"
import { validator } from "../../../../utils/validator" import { validator } from "../../../../utils/validator"
import { promiseAll } from "@medusajs/utils"
/** /**
* @oas [get] /store/variants * @oas [get] /store/variants
@@ -189,7 +190,7 @@ export default async (req, res) => {
sales_channel_id sales_channel_id
)) as any )) as any
) )
await Promise.all(decoratePromises) await promiseAll(decoratePromises)
res.json({ variants }) res.json({ variants })
} }
+2 -2
View File
@@ -1,4 +1,4 @@
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { AwilixContainer } from "awilix" import { AwilixContainer } from "awilix"
import { import {
BaseFulfillmentService, BaseFulfillmentService,
@@ -131,7 +131,7 @@ export default async ({
const context = { container, manager, logger } const context = { container, manager, logger }
await Promise.all([ await promiseAll([
registerPaymentProvider(context), registerPaymentProvider(context),
registerPaymentProcessor(context), registerPaymentProcessor(context),
registerNotificationProvider(context), registerNotificationProvider(context),
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import cors from "cors" import cors from "cors"
import { Express, json, urlencoded } from "express" import { Express, json, urlencoded } from "express"
import { readdir } from "fs/promises" import { readdir } from "fs/promises"
@@ -207,7 +208,7 @@ export class RoutesLoader {
* @return {Promise<void>} * @return {Promise<void>}
*/ */
protected async createRoutesConfig(): Promise<void> { protected async createRoutesConfig(): Promise<void> {
await Promise.all( await promiseAll(
[...this.routesMap.values()].map(async (descriptor: RouteDescriptor) => { [...this.routesMap.values()].map(async (descriptor: RouteDescriptor) => {
const absolutePath = descriptor.absolutePath const absolutePath = descriptor.absolutePath
@@ -400,7 +401,7 @@ export class RoutesLoader {
dirPath: string dirPath: string
parentPath?: string parentPath?: string
}): Promise<void> { }): Promise<void> {
await Promise.all( await promiseAll(
await readdir(dirPath, { withFileTypes: true }).then((entries) => { await readdir(dirPath, { withFileTypes: true }).then((entries) => {
return entries return entries
.filter((entry) => { .filter((entry) => {
+9 -9
View File
@@ -1,5 +1,5 @@
import { SearchUtils, upperCaseFirst } from "@medusajs/utils" import { promiseAll, SearchUtils, upperCaseFirst } from "@medusajs/utils"
import { Lifetime, aliasTo, asFunction, asValue } from "awilix" import { aliasTo, asFunction, asValue, Lifetime } from "awilix"
import { FileService, OauthService } from "medusa-interfaces" import { FileService, OauthService } from "medusa-interfaces"
import { import {
AbstractTaxService, AbstractTaxService,
@@ -73,13 +73,13 @@ export default async ({
}: Options): Promise<void> => { }: Options): Promise<void> => {
const resolved = getResolvedPlugins(rootDirectory, configModule) || [] const resolved = getResolvedPlugins(rootDirectory, configModule) || []
await Promise.all( await promiseAll(
resolved.map( resolved.map(
async (pluginDetails) => await runSetupFunctions(pluginDetails) async (pluginDetails) => await runSetupFunctions(pluginDetails)
) )
) )
await Promise.all( await promiseAll(
resolved.map(async (pluginDetails) => { resolved.map(async (pluginDetails) => {
registerRepositories(pluginDetails, container) registerRepositories(pluginDetails, container)
await registerServices(pluginDetails, container) await registerServices(pluginDetails, container)
@@ -97,7 +97,7 @@ export default async ({
}) })
) )
await Promise.all( await promiseAll(
resolved.map(async (pluginDetails) => runLoaders(pluginDetails, container)) resolved.map(async (pluginDetails) => runLoaders(pluginDetails, container))
) )
@@ -152,7 +152,7 @@ export async function registerPluginModels({
getResolvedPlugins(rootDirectory, configModule, extensionDirectoryPath) || getResolvedPlugins(rootDirectory, configModule, extensionDirectoryPath) ||
[] []
await Promise.all( await promiseAll(
resolved.map(async (pluginDetails) => { resolved.map(async (pluginDetails) => {
registerModels(pluginDetails, container, rootDirectory, pathGlob) registerModels(pluginDetails, container, rootDirectory, pathGlob)
}) })
@@ -167,7 +167,7 @@ async function runLoaders(
`${pluginDetails.resolve}/loaders/[!__]*.js`, `${pluginDetails.resolve}/loaders/[!__]*.js`,
{} {}
) )
await Promise.all( await promiseAll(
loaderFiles.map(async (loader) => { loaderFiles.map(async (loader) => {
try { try {
const module = require(loader).default const module = require(loader).default
@@ -419,7 +419,7 @@ export async function registerServices(
container: MedusaContainer container: MedusaContainer
): Promise<void> { ): Promise<void> {
const files = glob.sync(`${pluginDetails.resolve}/services/[!__]*.js`, {}) const files = glob.sync(`${pluginDetails.resolve}/services/[!__]*.js`, {})
await Promise.all( await promiseAll(
files.map(async (fn) => { files.map(async (fn) => {
const loaded = require(fn).default const loaded = require(fn).default
const name = formatRegistrationName(fn) const name = formatRegistrationName(fn)
@@ -668,7 +668,7 @@ function registerModels(
*/ */
async function runSetupFunctions(pluginDetails: PluginDetails): Promise<void> { async function runSetupFunctions(pluginDetails: PluginDetails): Promise<void> {
const files = glob.sync(`${pluginDetails.resolve}/setup/*.js`, {}) const files = glob.sync(`${pluginDetails.resolve}/setup/*.js`, {})
await Promise.all( await promiseAll(
files.map(async (fn) => { files.map(async (fn) => {
const loaded = require(fn).default const loaded = require(fn).default
try { try {
+2 -1
View File
@@ -2,6 +2,7 @@ import { FindOperator, FindOptionsWhere, ILike, In } from "typeorm"
import { Customer } from "../models" import { Customer } from "../models"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { ExtendedFindConfig } from "../types/common" import { ExtendedFindConfig } from "../types/common"
import { promiseAll } from "@medusajs/utils"
export const CustomerRepository = dataSource.getRepository(Customer).extend({ export const CustomerRepository = dataSource.getRepository(Customer).extend({
async listAndCount( async listAndCount(
@@ -43,7 +44,7 @@ export const CustomerRepository = dataSource.getRepository(Customer).extend({
] ]
} }
return await Promise.all([this.find(query_), this.count(query_)]) return await promiseAll([this.find(query_), this.count(query_)])
}, },
}) })
export default CustomerRepository export default CustomerRepository
@@ -2,6 +2,7 @@ import { FindOptionsWhere, ILike, Raw } from "typeorm"
import { GiftCard } from "../models" import { GiftCard } from "../models"
import { ExtendedFindConfig } from "../types/common" import { ExtendedFindConfig } from "../types/common"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { promiseAll } from "@medusajs/utils"
export const GiftCardRepository = dataSource.getRepository(GiftCard).extend({ export const GiftCardRepository = dataSource.getRepository(GiftCard).extend({
async listGiftCardsAndCount( async listGiftCardsAndCount(
@@ -34,7 +35,7 @@ export const GiftCardRepository = dataSource.getRepository(GiftCard).extend({
] ]
} }
return await Promise.all([this.find(query_), this.count(query_)]) return await promiseAll([this.find(query_), this.count(query_)])
}, },
}) })
export default GiftCardRepository export default GiftCardRepository
@@ -15,8 +15,6 @@ import {
PriceListPriceCreateInput, PriceListPriceCreateInput,
PriceListPriceUpdateInput, PriceListPriceUpdateInput,
} from "../types/price-list" } from "../types/price-list"
import { MedusaError } from "medusa-core-utils"
import { ProductVariantPrice } from "../types/product-variant" import { ProductVariantPrice } from "../types/product-variant"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
@@ -24,6 +22,7 @@ import { groupBy } from "lodash"
import { isString } from "../utils" import { isString } from "../utils"
import partition from "lodash/partition" import partition from "lodash/partition"
import { ulid } from "ulid" import { ulid } from "ulid"
import { promiseAll } from "@medusajs/utils"
type Price = Partial< type Price = Partial<
Omit<MoneyAmount, "created_at" | "updated_at" | "deleted_at"> Omit<MoneyAmount, "created_at" | "updated_at" | "deleted_at">
@@ -182,7 +181,7 @@ export const MoneyAmountRepository = dataSource
return return
} }
await Promise.all([ await promiseAll([
this.delete(deleteAmounts.map((mav) => mav.id)), this.delete(deleteAmounts.map((mav) => mav.id)),
mavDeleteQueryBuilder mavDeleteQueryBuilder
.where( .where(
@@ -558,7 +557,7 @@ export const MoneyAmountRepository = dataSource
[[], []] as [MoneyAmount[], ProductVariantMoneyAmount[]] [[], []] as [MoneyAmount[], ProductVariantMoneyAmount[]]
) )
const [prices] = await Promise.all([ const [prices] = await promiseAll([
this.save([...existingPrices, ...newPriceEntities]), this.save([...existingPrices, ...newPriceEntities]),
await this.manager.save(joinTableValues), await this.manager.save(joinTableValues),
]) ])
+2 -2
View File
@@ -1,4 +1,4 @@
import { objectToStringPath } from "@medusajs/utils" import { objectToStringPath, promiseAll } from "@medusajs/utils"
import { flatten } from "lodash" import { flatten } from "lodash"
import { FindManyOptions, FindOptionsRelations, In } from "typeorm" import { FindManyOptions, FindOptionsRelations, In } from "typeorm"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
@@ -21,7 +21,7 @@ export const OrderRepository = dataSource.getRepository(Order).extend({
const groupedRelations = getGroupedRelations(objectToStringPath(relations)) const groupedRelations = getGroupedRelations(objectToStringPath(relations))
const entitiesIdsWithRelations = await Promise.all( const entitiesIdsWithRelations = await promiseAll(
Object.entries(groupedRelations).map(async ([topLevel, rels]) => { Object.entries(groupedRelations).map(async ([topLevel, rels]) => {
// If top level is region or items then get deleted region as well // If top level is region or items then get deleted region as well
return this.find({ return this.find({
@@ -2,6 +2,7 @@ import { FindOperator, FindOptionsWhere, ILike, In } from "typeorm"
import { PriceList, ProductVariantMoneyAmount } from "../models" import { PriceList, ProductVariantMoneyAmount } from "../models"
import { ExtendedFindConfig } from "../types/common" import { ExtendedFindConfig } from "../types/common"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { promiseAll } from "@medusajs/utils"
export const PriceListRepository = dataSource.getRepository(PriceList).extend({ export const PriceListRepository = dataSource.getRepository(PriceList).extend({
async listAndCount( async listAndCount(
@@ -52,7 +53,7 @@ export const PriceListRepository = dataSource.getRepository(PriceList).extend({
] ]
} }
return await Promise.all([this.find(query_), this.count(query_)]) return await promiseAll([this.find(query_), this.count(query_)])
}, },
async listPriceListsVariantIdsMap( async listPriceListsVariantIdsMap(
@@ -8,7 +8,7 @@ import {
import { ProductCategory } from "../models/product-category" import { ProductCategory } from "../models/product-category"
import { ExtendedFindConfig, QuerySelector } from "../types/common" import { ExtendedFindConfig, QuerySelector } from "../types/common"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { objectToStringPath } from "@medusajs/utils" import { objectToStringPath, promiseAll } from "@medusajs/utils"
import { isEmpty } from "lodash" import { isEmpty } from "lodash"
export const ProductCategoryRepository = dataSource export const ProductCategoryRepository = dataSource
@@ -115,7 +115,7 @@ export const ProductCategoryRepository = dataSource
let [categories, count] = await queryBuilder.getManyAndCount() let [categories, count] = await queryBuilder.getManyAndCount()
categories = await Promise.all( categories = await promiseAll(
categories.map(async (productCategory) => { categories.map(async (productCategory) => {
if (includeTree) { if (includeTree) {
productCategory = await this.findDescendantsTree(productCategory) productCategory = await this.findDescendantsTree(productCategory)
@@ -1,6 +1,7 @@
import { ProductCollection } from "../models" import { ProductCollection } from "../models"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { ExtendedFindConfig } from "../types/common" import { ExtendedFindConfig } from "../types/common"
import { promiseAll } from "@medusajs/utils"
// eslint-disable-next-line max-len // eslint-disable-next-line max-len
export const ProductCollectionRepository = dataSource export const ProductCollectionRepository = dataSource
@@ -19,7 +20,7 @@ export const ProductCollectionRepository = dataSource
{ dcId: conditionId } { dcId: conditionId }
) )
return await Promise.all([qb.getMany(), qb.getCount()]) return await promiseAll([qb.getMany(), qb.getCount()])
}, },
}) })
export default ProductCollectionRepository export default ProductCollectionRepository
@@ -3,6 +3,7 @@ import { ProductTag } from "../models/product-tag"
import { ExtendedFindConfig } from "../types/common" import { ExtendedFindConfig } from "../types/common"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
import { promiseAll } from "@medusajs/utils"
type UpsertTagsInput = (Partial<ProductTag> & { type UpsertTagsInput = (Partial<ProductTag> & {
value: string value: string
@@ -101,7 +102,7 @@ export const ProductTagRepository = dataSource
{ dcId: conditionId } { dcId: conditionId }
) )
return await Promise.all([qb.getMany(), qb.getCount()]) return await promiseAll([qb.getMany(), qb.getCount()])
}, },
}) })
@@ -2,6 +2,7 @@ import { ProductType } from "../models"
import { ExtendedFindConfig } from "../types/common" import { ExtendedFindConfig } from "../types/common"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
import { promiseAll } from "@medusajs/utils"
type UpsertTypeInput = Partial<ProductType> & { type UpsertTypeInput = Partial<ProductType> & {
value: string value: string
@@ -55,7 +56,7 @@ export const ProductTypeRepository = dataSource
{ dcId: conditionId } { dcId: conditionId }
) )
return await Promise.all([qb.getMany(), qb.getCount()]) return await promiseAll([qb.getMany(), qb.getCount()])
}, },
}) })
export default ProductTypeRepository export default ProductTypeRepository
+3 -3
View File
@@ -16,7 +16,7 @@ import {
} from "../models" } from "../models"
import { TaxRateListByConfig } from "../types/tax-rate" import { TaxRateListByConfig } from "../types/tax-rate"
import { isDefined } from "medusa-core-utils" import { isDefined } from "medusa-core-utils"
import { objectToStringPath } from "@medusajs/utils" import { objectToStringPath, promiseAll } from "@medusajs/utils"
import { dataSource } from "../loaders/database" import { dataSource } from "../loaders/database"
const resolveableFields = [ const resolveableFields = [
@@ -68,7 +68,7 @@ export const TaxRateRepository = dataSource.getRepository(TaxRate).extend({
async findAndCountWithResolution(findOptions: FindManyOptions<TaxRate>) { async findAndCountWithResolution(findOptions: FindManyOptions<TaxRate>) {
const qb = this.getFindQueryBuilder(findOptions) const qb = this.getFindQueryBuilder(findOptions)
return await Promise.all([qb.getMany(), qb.getCount()]) return await promiseAll([qb.getMany(), qb.getCount()])
}, },
applyResolutionsToQueryBuilder( applyResolutionsToQueryBuilder(
@@ -246,7 +246,7 @@ export const TaxRateRepository = dataSource.getRepository(TaxRate).extend({
}) })
} }
const results = await Promise.all([ const results = await promiseAll([
productRates.getMany(), productRates.getMany(),
typeRates.getMany(), typeRates.getMany(),
]) ])
@@ -10,6 +10,7 @@ import { ProductVariant } from "../models"
import dotenv from "dotenv" import dotenv from "dotenv"
import express from "express" import express from "express"
import loaders from "../loaders" import loaders from "../loaders"
import { promiseAll } from "@medusajs/utils"
dotenv.config() dotenv.config()
@@ -99,7 +100,7 @@ const processBatch = async (
) => { ) => {
const manager = container.resolve("manager") const manager = container.resolve("manager")
return await manager.transaction(async (transactionManager) => { return await manager.transaction(async (transactionManager) => {
await Promise.all( await promiseAll(
variants.map(async (variant) => { variants.map(async (variant) => {
await migrateProductVariant(variant, locationId, { await migrateProductVariant(variant, locationId, {
container, container,
@@ -1,7 +1,5 @@
import { FlagRouter, MedusaError } from "@medusajs/utils" import { FlagRouter, MedusaError, promiseAll } from "@medusajs/utils"
import { IPricingModuleService, MedusaContainer } from "@medusajs/types" import { IPricingModuleService, MedusaContainer } from "@medusajs/types"
import { AwilixContainer } from "awilix"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import IsolatePricingDomainFeatureFlag from "../loaders/feature-flags/isolate-pricing-domain" import IsolatePricingDomainFeatureFlag from "../loaders/feature-flags/isolate-pricing-domain"
import { Modules } from "@medusajs/modules-sdk" import { Modules } from "@medusajs/modules-sdk"
@@ -69,7 +67,7 @@ const processBatch = async (
) => { ) => {
const manager = container.resolve("manager") const manager = container.resolve("manager")
return await manager.transaction(async (transactionManager) => { return await manager.transaction(async (transactionManager) => {
await Promise.all( await promiseAll(
variants.map(async (variant) => { variants.map(async (variant) => {
await migrateProductVariant(variant, { await migrateProductVariant(variant, {
container, container,
+34 -34
View File
@@ -197,40 +197,6 @@ class BatchJobService extends TransactionBaseService {
}) })
} }
protected async updateStatus(
batchJobOrId: BatchJob | string,
status: BatchJobStatus
): Promise<BatchJob | never> {
let batchJob: BatchJob = batchJobOrId as BatchJob
if (typeof batchJobOrId === "string") {
batchJob = await this.retrieve(batchJobOrId)
}
const { entityColumnName, eventType } =
this.batchJobStatusMapToProps.get(status) || {}
if (!entityColumnName || !eventType) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Unable to update the batch job status from ${batchJob.status} to ${status}. The status doesn't exist`
)
}
batchJob[entityColumnName] = new Date()
const batchJobRepo = this.activeManager_.withRepository(
this.batchJobRepository_
)
batchJob = await batchJobRepo.save(batchJob)
batchJob.loadStatus()
await this.eventBus_.withTransaction(this.activeManager_).emit(eventType, {
id: batchJob.id,
})
return batchJob
}
async confirm(batchJobOrId: string | BatchJob): Promise<BatchJob | never> { async confirm(batchJobOrId: string | BatchJob): Promise<BatchJob | never> {
return await this.atomicPhase_(async () => { return await this.atomicPhase_(async () => {
let batchJob: BatchJob = batchJobOrId as BatchJob let batchJob: BatchJob = batchJobOrId as BatchJob
@@ -377,6 +343,40 @@ class BatchJobService extends TransactionBaseService {
.prepareBatchJobForProcessing(data, req) .prepareBatchJobForProcessing(data, req)
}) })
} }
protected async updateStatus(
batchJobOrId: BatchJob | string,
status: BatchJobStatus
): Promise<BatchJob | never> {
let batchJob: BatchJob = batchJobOrId as BatchJob
if (typeof batchJobOrId === "string") {
batchJob = await this.retrieve(batchJobOrId)
}
const { entityColumnName, eventType } =
this.batchJobStatusMapToProps.get(status) || {}
if (!entityColumnName || !eventType) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Unable to update the batch job status from ${batchJob.status} to ${status}. The status doesn't exist`
)
}
batchJob[entityColumnName] = new Date()
const batchJobRepo = this.activeManager_.withRepository(
this.batchJobRepository_
)
batchJob = await batchJobRepo.save(batchJob)
batchJob.loadStatus()
await this.eventBus_.withTransaction(this.activeManager_).emit(eventType, {
id: batchJob.id,
})
return batchJob
}
} }
export default BatchJobService export default BatchJobService
+11 -11
View File
@@ -1,4 +1,4 @@
import { FlagRouter, isDefined, MedusaError } from "@medusajs/utils" import { FlagRouter, isDefined, MedusaError, promiseAll } from "@medusajs/utils"
import { isEmpty, isEqual } from "lodash" import { isEmpty, isEqual } from "lodash"
import { DeepPartial, EntityManager, In, IsNull, Not } from "typeorm" import { DeepPartial, EntityManager, In, IsNull, Not } from "typeorm"
import { import {
@@ -811,7 +811,7 @@ class CartService extends TransactionBaseService {
if (this.featureFlagRouter_.isFeatureEnabled("sales_channels")) { if (this.featureFlagRouter_.isFeatureEnabled("sales_channels")) {
if (config.validateSalesChannels) { if (config.validateSalesChannels) {
const areValid = await Promise.all( const areValid = await promiseAll(
items.map(async (item) => { items.map(async (item) => {
if (item.variant_id) { if (item.variant_id) {
return await this.validateLineItem( return await this.validateLineItem(
@@ -939,7 +939,7 @@ class CartService extends TransactionBaseService {
// Update all items that needs to be updated // Update all items that needs to be updated
if (itemKeysToUpdate.length) { if (itemKeysToUpdate.length) {
await Promise.all( await promiseAll(
itemKeysToUpdate.map(async (id) => { itemKeysToUpdate.map(async (id) => {
return await lineItemServiceTx.update(id, lineItemsToUpdate[id]) return await lineItemServiceTx.update(id, lineItemsToUpdate[id])
}) })
@@ -1130,7 +1130,7 @@ class CartService extends TransactionBaseService {
} }
) )
} else { } else {
await Promise.all( await promiseAll(
cart.shipping_methods.map(async (shippingMethod) => { cart.shipping_methods.map(async (shippingMethod) => {
// if free shipping discount is removed, we adjust the shipping // if free shipping discount is removed, we adjust the shipping
// back to its original amount // back to its original amount
@@ -1261,7 +1261,7 @@ class CartService extends TransactionBaseService {
if ("gift_cards" in data) { if ("gift_cards" in data) {
cart.gift_cards = [] cart.gift_cards = []
await Promise.all( await promiseAll(
(data.gift_cards ?? []).map(async ({ code }) => { (data.gift_cards ?? []).map(async ({ code }) => {
return this.applyGiftCard_(cart, code) return this.applyGiftCard_(cart, code)
}) })
@@ -1337,7 +1337,7 @@ class CartService extends TransactionBaseService {
}) })
if (itemsToRemove.length) { if (itemsToRemove.length) {
const results = await Promise.all( const results = await promiseAll(
itemsToRemove.map(async (item) => { itemsToRemove.map(async (item) => {
return this.removeLineItem(cart.id, item.id) return this.removeLineItem(cart.id, item.id)
}) })
@@ -1938,7 +1938,7 @@ class CartService extends TransactionBaseService {
// In the case of a cart that has a total <= 0 we can return prematurely. // In the case of a cart that has a total <= 0 we can return prematurely.
// we are deleting the sessions, and we don't need to create or update anything from now on. // we are deleting the sessions, and we don't need to create or update anything from now on.
if (total <= 0) { if (total <= 0) {
await Promise.all( await promiseAll(
cart.payment_sessions.map(async (session) => { cart.payment_sessions.map(async (session) => {
return deleteSessionAppropriately(session) return deleteSessionAppropriately(session)
}) })
@@ -1962,7 +1962,7 @@ class CartService extends TransactionBaseService {
amount: total, amount: total,
} }
await Promise.all( await promiseAll(
cart.payment_sessions.map(async (session) => { cart.payment_sessions.map(async (session) => {
if (!providerSet.has(session.provider_id)) { if (!providerSet.has(session.provider_id)) {
/** /**
@@ -2043,7 +2043,7 @@ class CartService extends TransactionBaseService {
return return
} }
await Promise.all( await promiseAll(
region.payment_providers.map(async (paymentProvider) => { region.payment_providers.map(async (paymentProvider) => {
if (alreadyConsumedProviderIds.has(paymentProvider.id)) { if (alreadyConsumedProviderIds.has(paymentProvider.id)) {
return return
@@ -2261,7 +2261,7 @@ class CartService extends TransactionBaseService {
) )
} }
await Promise.all( await promiseAll(
cart.items.map(async (item) => { cart.items.map(async (item) => {
return lineItemServiceTx.update(item.id, { return lineItemServiceTx.update(item.id, {
has_shipping: this.validateLineItemShipping_( has_shipping: this.validateLineItemShipping_(
@@ -2365,7 +2365,7 @@ class CartService extends TransactionBaseService {
}) })
cart.items = ( cart.items = (
await Promise.all( await promiseAll(
cart.items.map(async (item) => { cart.items.map(async (item) => {
if (!item.variant_id) { if (!item.variant_id) {
return item return item
+2 -1
View File
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import { isDefined, MedusaError } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { ClaimImage, ClaimItem, ClaimTag } from "../models" import { ClaimImage, ClaimItem, ClaimTag } from "../models"
@@ -79,7 +80,7 @@ class ClaimItemService extends TransactionBaseService {
let tagsToAdd: ClaimTag[] = [] let tagsToAdd: ClaimTag[] = []
if (tags && tags.length) { if (tags && tags.length) {
const claimTagRepo = manager.withRepository(this.claimTagRepository_) const claimTagRepo = manager.withRepository(this.claimTagRepository_)
tagsToAdd = await Promise.all( tagsToAdd = await promiseAll(
tags.map(async (t) => { tags.map(async (t) => {
const normalized = t.trim().toLowerCase() const normalized = t.trim().toLowerCase()
const existing = await claimTagRepo.findOne({ const existing = await claimTagRepo.findOne({
+3 -2
View File
@@ -34,6 +34,7 @@ import ReturnService from "./return"
import ShippingOptionService from "./shipping-option" import ShippingOptionService from "./shipping-option"
import TaxProviderService from "./tax-provider" import TaxProviderService from "./tax-provider"
import TotalsService from "./totals" import TotalsService from "./totals"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -377,7 +378,7 @@ export default class ClaimService extends TransactionBaseService {
let newItems: LineItem[] = [] let newItems: LineItem[] = []
if (isDefined(additional_items)) { if (isDefined(additional_items)) {
newItems = await Promise.all( newItems = await promiseAll(
additional_items.map(async (i) => additional_items.map(async (i) =>
lineItemServiceTx.generate( lineItemServiceTx.generate(
i.variant_id, i.variant_id,
@@ -387,7 +388,7 @@ export default class ClaimService extends TransactionBaseService {
) )
) )
await Promise.all( await promiseAll(
newItems.map(async (newItem) => { newItems.map(async (newItem) => {
if (newItem.variant_id) { if (newItem.variant_id) {
await this.productVariantInventoryService_.reserveQuantity( await this.productVariantInventoryService_.reserveQuantity(
+7 -7
View File
@@ -1,7 +1,7 @@
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { parse, toSeconds } from "iso8601-duration" import { parse, toSeconds } from "iso8601-duration"
import { isEmpty, omit } from "lodash" import { isEmpty, omit } from "lodash"
import { MedusaError, isDefined } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { import {
DeepPartial, DeepPartial,
EntityManager, EntityManager,
@@ -197,7 +197,7 @@ class DiscountService extends TransactionBaseService {
) )
} }
if (discount.regions) { if (discount.regions) {
discount.regions = (await Promise.all( discount.regions = (await promiseAll(
discount.regions.map(async (regionId) => discount.regions.map(async (regionId) =>
this.regionService_.withTransaction(manager).retrieve(regionId) this.regionService_.withTransaction(manager).retrieve(regionId)
) )
@@ -222,7 +222,7 @@ class DiscountService extends TransactionBaseService {
const result = await discountRepo.save(created) const result = await discountRepo.save(created)
if (conditions?.length) { if (conditions?.length) {
await Promise.all( await promiseAll(
conditions.map(async (cond) => { conditions.map(async (cond) => {
await this.discountConditionService_ await this.discountConditionService_
.withTransaction(manager) .withTransaction(manager)
@@ -373,7 +373,7 @@ class DiscountService extends TransactionBaseService {
} }
if (conditions?.length) { if (conditions?.length) {
await Promise.all( await promiseAll(
conditions.map(async (cond) => { conditions.map(async (cond) => {
await this.discountConditionService_ await this.discountConditionService_
.withTransaction(manager) .withTransaction(manager)
@@ -383,7 +383,7 @@ class DiscountService extends TransactionBaseService {
} }
if (regions) { if (regions) {
discount.regions = await Promise.all( discount.regions = await promiseAll(
regions.map(async (regionId) => regions.map(async (regionId) =>
this.regionService_.retrieve(regionId) this.regionService_.retrieve(regionId)
) )
@@ -675,7 +675,7 @@ class DiscountService extends TransactionBaseService {
): Promise<void> { ): Promise<void> {
const discounts = Array.isArray(discount) ? discount : [discount] const discounts = Array.isArray(discount) ? discount : [discount]
return await this.atomicPhase_(async () => { return await this.atomicPhase_(async () => {
await Promise.all( await promiseAll(
discounts.map(async (disc) => { discounts.map(async (disc) => {
if (this.hasReachedLimit(disc)) { if (this.hasReachedLimit(disc)) {
throw new MedusaError( throw new MedusaError(
+2 -2
View File
@@ -29,7 +29,7 @@ import EventBusService from "./event-bus"
import LineItemService from "./line-item" import LineItemService from "./line-item"
import ProductVariantService from "./product-variant" import ProductVariantService from "./product-variant"
import ShippingOptionService from "./shipping-option" import ShippingOptionService from "./shipping-option"
import { isDefined } from "@medusajs/utils" import { isDefined, promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -400,7 +400,7 @@ class DraftOrderService extends TransactionBaseService {
) )
}) })
await Promise.all(promises) await promiseAll(promises)
if (discounts?.length) { if (discounts?.length) {
await cartServiceTx.update(createdCart.id, { discounts }) await cartServiceTx.update(createdCart.id, { discounts })
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import BaseFulfillmentService from "medusa-interfaces" import BaseFulfillmentService from "medusa-interfaces"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
@@ -75,7 +76,7 @@ class FulfillmentProviderService extends TransactionBaseService {
async listFulfillmentOptions( async listFulfillmentOptions(
providerIds: string[] providerIds: string[]
): Promise<FulfillmentOptions[]> { ): Promise<FulfillmentOptions[]> {
return await Promise.all( return await promiseAll(
providerIds.map(async (p) => { providerIds.map(async (p) => {
const provider = this.retrieveProvider(p) const provider = this.retrieveProvider(p)
return { return {
+4 -3
View File
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import { isDefined, MedusaError } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { ProductVariantInventoryService, ShippingProfileService } from "." import { ProductVariantInventoryService, ShippingProfileService } from "."
@@ -110,7 +111,7 @@ class FulfillmentService extends TransactionBaseService {
order: CreateFulfillmentOrder, order: CreateFulfillmentOrder,
items: FulFillmentItemType[] items: FulFillmentItemType[]
): Promise<(LineItem | null)[]> { ): Promise<(LineItem | null)[]> {
const toReturn = await Promise.all( const toReturn = await promiseAll(
items.map(async ({ item_id, quantity }) => { items.map(async ({ item_id, quantity }) => {
const item = order.items.find((i) => i.id === item_id) const item = order.items.find((i) => i.id === item_id)
return this.validateFulfillmentLineItem_(item, quantity) return this.validateFulfillmentLineItem_(item, quantity)
@@ -222,7 +223,7 @@ class FulfillmentService extends TransactionBaseService {
lineItems as LineItem[] lineItems as LineItem[]
) )
const created = await Promise.all( const created = await promiseAll(
fulfillments.map(async ({ shipping_method, items }) => { fulfillments.map(async ({ shipping_method, items }) => {
const ful = fulfillmentRepository.create({ const ful = fulfillmentRepository.create({
...custom, ...custom,
@@ -283,7 +284,7 @@ class FulfillmentService extends TransactionBaseService {
const lineItemServiceTx = this.lineItemService_.withTransaction(manager) const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
await Promise.all( await promiseAll(
fulfillment.items.map(async (fItem) => { fulfillment.items.map(async (fItem) => {
const item = await lineItemServiceTx.retrieve(fItem.item_id) const item = await lineItemServiceTx.retrieve(fItem.item_id)
const fulfilledQuantity = item.fulfilled_quantity! - fItem.quantity const fulfilledQuantity = item.fulfilled_quantity! - fItem.quantity
@@ -1,6 +1,7 @@
import { Job, Queue, Worker } from "bullmq" import { Job, Queue, Worker } from "bullmq"
import Redis from "ioredis" import Redis from "ioredis"
import { ConfigModule, Logger } from "../types/global" import { ConfigModule, Logger } from "../types/global"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
logger: Logger logger: Logger
@@ -86,7 +87,7 @@ export default class JobSchedulerService {
const observers = this.handlers_.get(eventName) || [] const observers = this.handlers_.get(eventName) || []
this.logger_.info(`Processing scheduled job: ${eventName}`) this.logger_.info(`Processing scheduled job: ${eventName}`)
return await Promise.all( return await promiseAll(
observers.map(async (subscriber) => { observers.map(async (subscriber) => {
return subscriber(data, eventName).catch((err) => { return subscriber(data, eventName).catch((err) => {
this.logger_.warn( this.logger_.warn(
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import { isDefined, MedusaError } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { EntityManager, FindOperator, In } from "typeorm" import { EntityManager, FindOperator, In } from "typeorm"
@@ -299,7 +300,7 @@ class LineItemAdjustmentService extends TransactionBaseService {
return [] return []
} }
return await Promise.all( return await promiseAll(
cart.items.map(async (li) => this.createAdjustmentForLineItem(cart, li)) cart.items.map(async (li) => this.createAdjustmentForLineItem(cart, li))
) )
} }
+2 -1
View File
@@ -11,6 +11,7 @@ import { Notification } from "../models"
import { NotificationProviderRepository } from "../repositories/notification-provider" import { NotificationProviderRepository } from "../repositories/notification-provider"
import { NotificationRepository } from "../repositories/notification" import { NotificationRepository } from "../repositories/notification"
import { buildQuery } from "../utils" import { buildQuery } from "../utils"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -194,7 +195,7 @@ class NotificationService extends TransactionBaseService {
return Promise.resolve() return Promise.resolve()
} }
return Promise.all( return promiseAll(
subs.map(async (providerId) => { subs.map(async (providerId) => {
return this.send(eventName, data, providerId).catch((err) => { return this.send(eventName, data, providerId).catch((err) => {
console.log(err) console.log(err)
@@ -9,6 +9,7 @@ import { CreateOrderEditItemChangeInput } from "../types/order-edit"
import { buildQuery } from "../utils" import { buildQuery } from "../utils"
import { LineItemService } from "./index" import { LineItemService } from "./index"
import TaxProviderService from "./tax-provider" import TaxProviderService from "./tax-provider"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -119,7 +120,7 @@ export default class OrderEditItemChangeService extends TransactionBaseService {
await orderItemChangeRepo.delete({ id: In(itemChangeIds as string[]) }) await orderItemChangeRepo.delete({ id: In(itemChangeIds as string[]) })
const lineItemServiceTx = this.lineItemService_.withTransaction(manager) const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
await Promise.all([ await promiseAll([
...lineItemIdsToRemove.map( ...lineItemIdsToRemove.map(
async (id) => await lineItemServiceTx.delete(id) async (id) => await lineItemServiceTx.delete(id)
), ),
+5 -4
View File
@@ -33,6 +33,7 @@ import EventBusService from "./event-bus"
import { IInventoryService } from "@medusajs/types" import { IInventoryService } from "@medusajs/types"
import { OrderEditRepository } from "../repositories/order-edit" import { OrderEditRepository } from "../repositories/order-edit"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -521,7 +522,7 @@ export default class OrderEditService extends TransactionBaseService {
}) })
const computedOrder = { ...order, items } as Order const computedOrder = { ...order, items } as Order
await Promise.all([ await promiseAll([
await orderServiceTx.decorateTotals(computedOrder), await orderServiceTx.decorateTotals(computedOrder),
await orderServiceTx.decorateTotals(order), await orderServiceTx.decorateTotals(order),
]) ])
@@ -752,7 +753,7 @@ export default class OrderEditService extends TransactionBaseService {
const lineItemServiceTx = this.lineItemService_.withTransaction(manager) const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
const [lineItems] = await Promise.all([ const [lineItems] = await promiseAll([
lineItemServiceTx.update( lineItemServiceTx.update(
{ order_id: orderEdit.order_id }, { order_id: orderEdit.order_id },
{ order_id: null } { order_id: null }
@@ -840,7 +841,7 @@ export default class OrderEditService extends TransactionBaseService {
orderEdit.changes.map((change) => change.id) orderEdit.changes.map((change) => change.id)
) )
await Promise.all( await promiseAll(
[ [
taxProviderServiceTs.clearLineItemsTaxLines(clonedItemIds), taxProviderServiceTs.clearLineItemsTaxLines(clonedItemIds),
clonedItemIds.map(async (id) => { clonedItemIds.map(async (id) => {
@@ -851,7 +852,7 @@ export default class OrderEditService extends TransactionBaseService {
].flat() ].flat()
) )
await Promise.all( await promiseAll(
clonedItemIds.map(async (id) => { clonedItemIds.map(async (id) => {
return await lineItemServiceTx.delete(id) return await lineItemServiceTx.delete(id)
}) })
+10 -9
View File
@@ -5,6 +5,7 @@ import {
FlagRouter, FlagRouter,
isDefined, isDefined,
MedusaError, MedusaError,
promiseAll,
} from "@medusajs/utils" } from "@medusajs/utils"
import { import {
EntityManager, EntityManager,
@@ -302,7 +303,7 @@ class OrderService extends TransactionBaseService {
const raw = await orderRepo.findWithRelations(rels, query) const raw = await orderRepo.findWithRelations(rels, query)
const count = await orderRepo.count(query) const count = await orderRepo.count(query)
const orders = await Promise.all( const orders = await promiseAll(
raw.map(async (r) => await this.decorateTotals(r, totalsToSelect)) raw.map(async (r) => await this.decorateTotals(r, totalsToSelect))
) )
@@ -768,22 +769,22 @@ class OrderService extends TransactionBaseService {
this.shippingOptionService_.withTransaction(manager) this.shippingOptionService_.withTransaction(manager)
const lineItemServiceTx = this.lineItemService_.withTransaction(manager) const lineItemServiceTx = this.lineItemService_.withTransaction(manager)
await Promise.all( await promiseAll(
[ [
cart.items.map((lineItem): unknown[] => { cart.items.map((lineItem): Promise<unknown>[] => {
const toReturn: unknown[] = [ const toReturn: Promise<unknown>[] = [
lineItemServiceTx.update(lineItem.id, { order_id: order.id }), lineItemServiceTx.update(lineItem.id, { order_id: order.id }),
] ]
if (lineItem.is_giftcard) { if (lineItem.is_giftcard) {
toReturn.push( toReturn.push(
this.createGiftCardsFromLineItem_(order, lineItem, manager) ...this.createGiftCardsFromLineItem_(order, lineItem, manager)
) )
} }
return toReturn return toReturn
}), }),
cart.shipping_methods.map(async (method) => { cart.shipping_methods.map(async (method): Promise<unknown> => {
// TODO: Due to cascade insert we have to remove the tax_lines that have been added by the cart decorate totals. // TODO: Due to cascade insert we have to remove the tax_lines that have been added by the cart decorate totals.
// Is the cascade insert really used? Also, is it really necessary to pass the entire entities when creating or updating? // Is the cascade insert really used? Also, is it really necessary to pass the entire entities when creating or updating?
// We normally should only pass what is needed? // We normally should only pass what is needed?
@@ -1225,7 +1226,7 @@ class OrderService extends TransactionBaseService {
const inventoryServiceTx = const inventoryServiceTx =
this.productVariantInventoryService_.withTransaction(manager) this.productVariantInventoryService_.withTransaction(manager)
await Promise.all( await promiseAll(
order.items.map(async (item) => { order.items.map(async (item) => {
if (item.variant_id) { if (item.variant_id) {
return await inventoryServiceTx.deleteReservationsByLineItem( return await inventoryServiceTx.deleteReservationsByLineItem(
@@ -1544,7 +1545,7 @@ class OrderService extends TransactionBaseService {
transformer: (item: LineItem | undefined, quantity: number) => unknown transformer: (item: LineItem | undefined, quantity: number) => unknown
): Promise<LineItem[]> { ): Promise<LineItem[]> {
return ( return (
await Promise.all( await promiseAll(
items.map(async ({ item_id, quantity }) => { items.map(async ({ item_id, quantity }) => {
const item = order.items.find((i) => i.id === item_id) const item = order.items.find((i) => i.id === item_id)
return transformer(item, quantity) return transformer(item, quantity)
@@ -1662,7 +1663,7 @@ class OrderService extends TransactionBaseService {
await this.totalsService_.getCalculationContext(order, { await this.totalsService_.getCalculationContext(order, {
exclude_shipping: true, exclude_shipping: true,
}) })
order.items = await Promise.all( order.items = await promiseAll(
(order.items || []).map(async (item) => { (order.items || []).map(async (item) => {
const itemTotals = await this.totalsService_.getLineItemTotals( const itemTotals = await this.totalsService_.getLineItemTotals(
item, item,
@@ -20,6 +20,7 @@ import {
PaymentCollectionsSessionsInput, PaymentCollectionsSessionsInput,
} from "../types/payment-collection" } from "../types/payment-collection"
import EventBusService from "./event-bus" import EventBusService from "./event-bus"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -336,7 +337,7 @@ export default class PaymentCollectionService extends TransactionBaseService {
const paymentProviderTx = const paymentProviderTx =
this.paymentProviderService_.withTransaction(manager) this.paymentProviderService_.withTransaction(manager)
Promise.all( await promiseAll(
removeSessions.map(async (sess) => removeSessions.map(async (sess) =>
paymentProviderTx.deleteSession(sess) paymentProviderTx.deleteSession(sess)
) )
@@ -1,4 +1,4 @@
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { isDefined, MedusaError } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { BasePaymentService } from "medusa-interfaces" import { BasePaymentService } from "medusa-interfaces"
import { EOL } from "os" import { EOL } from "os"
@@ -87,7 +87,7 @@ export default class PaymentProviderService extends TransactionBaseService {
) )
await model.update({}, { is_installed: false }) await model.update({}, { is_installed: false })
await Promise.all( await promiseAll(
providerIds.map(async (providerId) => { providerIds.map(async (providerId) => {
const provider = model.create({ const provider = model.create({
id: providerId, id: providerId,
+4 -4
View File
@@ -13,7 +13,7 @@ import { isDefined, MedusaError } from "medusa-core-utils"
import { CustomerGroupService } from "." import { CustomerGroupService } from "."
import { FilterableProductProps } from "../types/product" import { FilterableProductProps } from "../types/product"
import { FilterableProductVariantProps } from "../types/product-variant" import { FilterableProductVariantProps } from "../types/product-variant"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { MoneyAmountRepository } from "../repositories/money-amount" import { MoneyAmountRepository } from "../repositories/money-amount"
import { PriceListRepository } from "../repositories/price-list" import { PriceListRepository } from "../repositories/price-list"
import ProductService from "./product" import ProductService from "./product"
@@ -384,10 +384,10 @@ class PriceListService extends TransactionBaseService {
const moneyAmountRepo = manager.withRepository(this.moneyAmountRepo_) const moneyAmountRepo = manager.withRepository(this.moneyAmountRepo_)
const productsWithPrices = await Promise.all( const productsWithPrices = await promiseAll(
products.map(async (p) => { products.map(async (p) => {
if (p.variants?.length) { if (p.variants?.length) {
p.variants = await Promise.all( p.variants = await promiseAll(
p.variants.map(async (v) => { p.variants.map(async (v) => {
const [prices] = const [prices] =
await moneyAmountRepo.findManyForVariantInPriceList( await moneyAmountRepo.findManyForVariantInPriceList(
@@ -431,7 +431,7 @@ class PriceListService extends TransactionBaseService {
const moneyAmountRepo = manager.withRepository(this.moneyAmountRepo_) const moneyAmountRepo = manager.withRepository(this.moneyAmountRepo_)
const variantsWithPrices = await Promise.all( const variantsWithPrices = await promiseAll(
variants.map(async (variant) => { variants.map(async (variant) => {
const [prices] = await moneyAmountRepo.findManyForVariantInPriceList( const [prices] = await moneyAmountRepo.findManyForVariantInPriceList(
variant.id, variant.id,
+4 -4
View File
@@ -4,7 +4,7 @@ import {
PriceSetMoneyAmountDTO, PriceSetMoneyAmountDTO,
RemoteQueryFunction, RemoteQueryFunction,
} from "@medusajs/types" } from "@medusajs/types"
import { FlagRouter, removeNullish } from "@medusajs/utils" import { FlagRouter, promiseAll, removeNullish } from "@medusajs/utils"
import { import {
IPriceSelectionStrategy, IPriceSelectionStrategy,
PriceSelectionContext, PriceSelectionContext,
@@ -501,7 +501,7 @@ class PricingService extends TransactionBaseService {
Record<string, ProductVariantPricing> Record<string, ProductVariantPricing>
>() >()
await Promise.all( await promiseAll(
data.map(async ({ productId, variants }) => { data.map(async ({ productId, variants }) => {
const pricingData = variants.map((variant) => { const pricingData = variants.map((variant) => {
return { variantId: variant.id } return { variantId: variant.id }
@@ -876,7 +876,7 @@ class PricingService extends TransactionBaseService {
regions.add(shippingOption.region_id) regions.add(shippingOption.region_id)
} }
const contexts = await Promise.all( const contexts = await promiseAll(
[...regions].map(async (regionId) => { [...regions].map(async (regionId) => {
return { return {
context: await this.collectPricingContext({ context: await this.collectPricingContext({
@@ -907,7 +907,7 @@ class PricingService extends TransactionBaseService {
) )
}) })
return await Promise.all(shippingOptionPricingPromises) return await promiseAll(shippingOptionPricingPromises)
} }
} }
@@ -9,7 +9,7 @@ import {
ReserveQuantityContext, ReserveQuantityContext,
} from "@medusajs/types" } from "@medusajs/types"
import { LineItem, Product, ProductVariant } from "../models" import { LineItem, Product, ProductVariant } from "../models"
import { isDefined, MedusaError } from "@medusajs/utils" import { isDefined, MedusaError, promiseAll } from "@medusajs/utils"
import { PricedProduct, PricedVariant } from "../types/pricing" import { PricedProduct, PricedVariant } from "../types/pricing"
import { ProductVariantInventoryItem } from "../models/product-variant-inventory-item" import { ProductVariantInventoryItem } from "../models/product-variant-inventory-item"
@@ -128,7 +128,7 @@ class ProductVariantInventoryService extends TransactionBaseService {
return false return false
} }
const hasInventory = await Promise.all( const hasInventory = await promiseAll(
variantInventory.map(async (inventoryPart) => { variantInventory.map(async (inventoryPart) => {
const itemQuantity = inventoryPart.required_quantity * quantity const itemQuantity = inventoryPart.required_quantity * quantity
return await this.inventoryService_.confirmInventory( return await this.inventoryService_.confirmInventory(
@@ -379,7 +379,7 @@ class ProductVariantInventoryService extends TransactionBaseService {
) )
const toCreate = ( const toCreate = (
await Promise.all( await promiseAll(
data.map(async (d) => { data.map(async (d) => {
if (existingMap.get(d.variantId)?.has(d.inventoryItemId)) { if (existingMap.get(d.variantId)?.has(d.inventoryItemId)) {
return null return null
@@ -766,7 +766,7 @@ class ProductVariantInventoryService extends TransactionBaseService {
return return
} }
await Promise.all( await promiseAll(
variantInventory.map(async (inventoryPart) => { variantInventory.map(async (inventoryPart) => {
const itemQuantity = inventoryPart.required_quantity * quantity const itemQuantity = inventoryPart.required_quantity * quantity
return await this.inventoryService_.adjustInventory( return await this.inventoryService_.adjustInventory(
@@ -797,7 +797,7 @@ class ProductVariantInventoryService extends TransactionBaseService {
availabilityContext availabilityContext
) )
return await Promise.all( return await promiseAll(
variants.map(async (variant) => { variants.map(async (variant) => {
if (!variant.id) { if (!variant.id) {
return variant return variant
@@ -924,7 +924,7 @@ class ProductVariantInventoryService extends TransactionBaseService {
salesChannelId salesChannelId
) )
return await Promise.all( return await promiseAll(
products.map(async (product) => { products.map(async (product) => {
if (!product.variants || product.variants.length === 0) { if (!product.variants || product.variants.length === 0) {
return product return product
@@ -971,7 +971,7 @@ class ProductVariantInventoryService extends TransactionBaseService {
this.salesChannelInventoryService_.withTransaction(this.activeManager_) this.salesChannelInventoryService_.withTransaction(this.activeManager_)
return Math.min( return Math.min(
...(await Promise.all( ...(await promiseAll(
variantInventoryItems.map(async (variantInventory) => { variantInventoryItems.map(async (variantInventory) => {
// get the total available quantity for the given sales channel // get the total available quantity for the given sales channel
// divided by the required quantity to account for how many of the // divided by the required quantity to account for how many of the
@@ -30,7 +30,7 @@ import {
PriceSelectionContext, PriceSelectionContext,
TransactionBaseService, TransactionBaseService,
} from "../interfaces" } from "../interfaces"
import { MedusaError, isDefined } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { import {
MoneyAmount, MoneyAmount,
Product, Product,
@@ -52,7 +52,7 @@ import { ProductOptionValueRepository } from "../repositories/product-option-val
import { ProductRepository } from "../repositories/product" import { ProductRepository } from "../repositories/product"
import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity" import { QueryDeepPartialEntity } from "typeorm/query-builder/QueryPartialEntity"
import RegionService from "./region" import RegionService from "./region"
import { buildRelations } from "@medusajs/utils" import { buildRelations, promiseAll } from "@medusajs/utils"
class ProductVariantService extends TransactionBaseService { class ProductVariantService extends TransactionBaseService {
static Events = { static Events = {
@@ -208,7 +208,7 @@ class ProductVariantService extends TransactionBaseService {
prices: ProductVariantPrice[] prices: ProductVariantPrice[]
}[] = [] }[] = []
const results = await Promise.all( const results = await promiseAll(
variants_.map(async (variant) => { variants_.map(async (variant) => {
const { prices, ...rest } = variant const { prices, ...rest } = variant
@@ -354,7 +354,7 @@ class ProductVariantService extends TransactionBaseService {
} }
const results: [ProductVariant, UpdateProductVariantInput, boolean][] = const results: [ProductVariant, UpdateProductVariantInput, boolean][] =
await Promise.all( await promiseAll(
variantData.map(async ({ variant, updateData }) => { variantData.map(async ({ variant, updateData }) => {
const { prices, options, ...rest } = updateData const { prices, options, ...rest } = updateData
@@ -533,7 +533,7 @@ class ProductVariantService extends TransactionBaseService {
promises.push(this.upsertCurrencyPrices(dataCurrencyPrices)) promises.push(this.upsertCurrencyPrices(dataCurrencyPrices))
} }
await Promise.all(promises) await promiseAll(promises)
}) })
} }
@@ -611,7 +611,7 @@ class ProductVariantService extends TransactionBaseService {
) )
} }
await Promise.all(promises) await promiseAll(promises)
}) })
} }
@@ -693,7 +693,7 @@ class ProductVariantService extends TransactionBaseService {
) )
} }
await Promise.all(promises) await promiseAll(promises)
}) })
} }
+4 -3
View File
@@ -3,6 +3,7 @@ import {
buildSelects, buildSelects,
FlagRouter, FlagRouter,
objectToStringPath, objectToStringPath,
promiseAll,
} from "@medusajs/utils" } from "@medusajs/utils"
import { isDefined, MedusaError } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { EntityManager, In } from "typeorm" import { EntityManager, In } from "typeorm"
@@ -494,7 +495,7 @@ class ProductService extends TransactionBaseService {
product = await productRepo.save(product) product = await productRepo.save(product)
product.options = await Promise.all( product.options = await promiseAll(
(options ?? []).map(async (option) => { (options ?? []).map(async (option) => {
const res = optionRepo.create({ const res = optionRepo.create({
...option, ...option,
@@ -658,7 +659,7 @@ class ProductService extends TransactionBaseService {
} }
} }
await Promise.all(promises) await promiseAll(promises)
const result = await productRepo.save(product) const result = await productRepo.save(product)
@@ -924,7 +925,7 @@ class ProductService extends TransactionBaseService {
(o) => o.option_id === optionId (o) => o.option_id === optionId
)?.value )?.value
const equalsFirst = await Promise.all( const equalsFirst = await promiseAll(
product.variants.map(async (v) => { product.variants.map(async (v) => {
const option = v.options.find((o) => o.option_id === optionId) const option = v.options.find((o) => o.option_id === optionId)
return option?.value === valueToMatch return option?.value === valueToMatch
+5 -5
View File
@@ -1,11 +1,11 @@
import { MedusaError, isDefined } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { DeepPartial, EntityManager } from "typeorm" import { DeepPartial, EntityManager } from "typeorm"
import { Country, Currency, Region } from "../models" import { Country, Currency, Region } from "../models"
import { FindConfig, Selector } from "../types/common" import { FindConfig, Selector } from "../types/common"
import { CreateRegionInput, UpdateRegionInput } from "../types/region" import { CreateRegionInput, UpdateRegionInput } from "../types/region"
import { buildQuery, setMetadata } from "../utils" import { buildQuery, setMetadata } from "../utils"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing" import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing"
import { CountryRepository } from "../repositories/country" import { CountryRepository } from "../repositories/country"
@@ -260,7 +260,7 @@ class RegionService extends TransactionBaseService {
} }
if (regionData.countries) { if (regionData.countries) {
region.countries = await Promise.all( region.countries = await promiseAll(
regionData.countries!.map(async (countryCode) => regionData.countries!.map(async (countryCode) =>
this.validateCountry(countryCode, id!) this.validateCountry(countryCode, id!)
) )
@@ -282,7 +282,7 @@ class RegionService extends TransactionBaseService {
} }
if (regionData.payment_providers) { if (regionData.payment_providers) {
region.payment_providers = await Promise.all( region.payment_providers = await promiseAll(
regionData.payment_providers.map(async (pId) => { regionData.payment_providers.map(async (pId) => {
const pp = await ppRepository.findOne({ where: { id: pId } }) const pp = await ppRepository.findOne({ where: { id: pId } })
if (!pp) { if (!pp) {
@@ -298,7 +298,7 @@ class RegionService extends TransactionBaseService {
} }
if (regionData.fulfillment_providers) { if (regionData.fulfillment_providers) {
region.fulfillment_providers = await Promise.all( region.fulfillment_providers = await promiseAll(
regionData.fulfillment_providers.map(async (fId) => { regionData.fulfillment_providers.map(async (fId) => {
const fp = await fpRepository.findOne({ where: { id: fId } }) const fp = await fpRepository.findOne({ where: { id: fId } })
if (!fp) { if (!fp) {
+4 -4
View File
@@ -20,10 +20,10 @@ import {
ReturnItem, ReturnItem,
ReturnStatus, ReturnStatus,
} from "../models" } from "../models"
import { MedusaError, isDefined } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing" import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing"
import { buildQuery, setMetadata, calculatePriceTaxAmount } from "../utils" import { buildQuery, calculatePriceTaxAmount, setMetadata } from "../utils"
import { OrdersReturnItem } from "../types/orders" import { OrdersReturnItem } from "../types/orders"
import { ReturnItemRepository } from "../repositories/return-item" import { ReturnItemRepository } from "../repositories/return-item"
@@ -129,7 +129,7 @@ class ReturnService extends TransactionBaseService {
} }
} }
const toReturn = await Promise.all( const toReturn = await promiseAll(
items.map(async (data) => { items.map(async (data) => {
const item = merged.find((i) => i.id === data.item_id) const item = merged.find((i) => i.id === data.item_id)
return transformer(item, data.quantity, data) return transformer(item, data.quantity, data)
@@ -1,4 +1,4 @@
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { isDefined, MedusaError } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
@@ -617,7 +617,7 @@ class ShippingOptionService extends TransactionBaseService {
const toRemove = option.requirements.filter( const toRemove = option.requirements.filter(
(r) => !accReqs.includes(r.id) (r) => !accReqs.includes(r.id)
) )
await Promise.all( await promiseAll(
toRemove.map(async (req) => { toRemove.map(async (req) => {
await this.removeRequirement(req.id) await this.removeRequirement(req.id)
}) })
@@ -1,4 +1,4 @@
import { FlagRouter, isDefined } from "@medusajs/utils" import { FlagRouter, isDefined, promiseAll } from "@medusajs/utils"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { EntityManager, In } from "typeorm" import { EntityManager, In } from "typeorm"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
@@ -498,7 +498,7 @@ class ShippingProfileService extends TransactionBaseService {
} }
return ( return (
await Promise.all( await promiseAll(
rawOpts.map(async (so) => { rawOpts.map(async (so) => {
return await this.shippingOptionService_ return await this.shippingOptionService_
.withTransaction(manager) .withTransaction(manager)
+2 -1
View File
@@ -9,6 +9,7 @@ import { UpdateStoreInput } from "../types/store"
import { buildQuery, setMetadata } from "../utils" import { buildQuery, setMetadata } from "../utils"
import { currencies } from "../utils/currencies" import { currencies } from "../utils/currencies"
import EventBusService from "./event-bus" import EventBusService from "./event-bus"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
manager: EntityManager manager: EntityManager
@@ -151,7 +152,7 @@ class StoreService extends TransactionBaseService {
) )
} }
store.currencies = await Promise.all( store.currencies = await promiseAll(
storeCurrencies.map(async (curr) => { storeCurrencies.map(async (curr) => {
const currency = await currencyRepository.findOne({ const currency = await currencyRepository.findOne({
where: { code: curr.toLowerCase() }, where: { code: curr.toLowerCase() },
+6 -5
View File
@@ -29,13 +29,14 @@ import {
} from "./index" } from "./index"
import { EntityManager, In } from "typeorm" import { EntityManager, In } from "typeorm"
import { FindConfig, Selector, WithRequiredProperty } from "../types/common" import { FindConfig, Selector, WithRequiredProperty } from "../types/common"
import { MedusaError, isDefined } from "medusa-core-utils" import { isDefined, MedusaError } from "medusa-core-utils"
import { buildQuery, setMetadata, validateId } from "../utils" import { buildQuery, setMetadata, validateId } from "../utils"
import { CreateShipmentConfig } from "../types/fulfillment" import { CreateShipmentConfig } from "../types/fulfillment"
import { OrdersReturnItem } from "../types/orders" import { OrdersReturnItem } from "../types/orders"
import { SwapRepository } from "../repositories/swap" import { SwapRepository } from "../repositories/swap"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { promiseAll } from "@medusajs/utils"
type InjectedProps = { type InjectedProps = {
manager: EntityManager manager: EntityManager
@@ -358,7 +359,7 @@ class SwapService extends TransactionBaseService {
let newItems: LineItem[] = [] let newItems: LineItem[] = []
if (additionalItems) { if (additionalItems) {
newItems = await Promise.all( newItems = await promiseAll(
additionalItems.map(async ({ variant_id, quantity }) => { additionalItems.map(async ({ variant_id, quantity }) => {
if (variant_id === null) { if (variant_id === null) {
throw new MedusaError( throw new MedusaError(
@@ -652,7 +653,7 @@ class SwapService extends TransactionBaseService {
const lineItemAdjustmentServiceTx = const lineItemAdjustmentServiceTx =
this.lineItemAdjustmentService_.withTransaction(manager) this.lineItemAdjustmentService_.withTransaction(manager)
await Promise.all( await promiseAll(
swap.additional_items.map( swap.additional_items.map(
async (item) => async (item) =>
await lineItemServiceTx.update(item.id, { await lineItemServiceTx.update(item.id, {
@@ -673,7 +674,7 @@ class SwapService extends TransactionBaseService {
], ],
}) })
await Promise.all( await promiseAll(
cart.items.map(async (item) => { cart.items.map(async (item) => {
// we generate adjustments in case the cart has any discounts that should be applied to the additional items // we generate adjustments in case the cart has any discounts that should be applied to the additional items
await lineItemAdjustmentServiceTx.createAdjustmentForLineItem( await lineItemAdjustmentServiceTx.createAdjustmentForLineItem(
@@ -790,7 +791,7 @@ class SwapService extends TransactionBaseService {
order_id: swap.order_id, order_id: swap.order_id,
}) })
await Promise.all( await promiseAll(
items.map(async (item) => { items.map(async (item) => {
if (item.variant_id) { if (item.variant_id) {
await this.productVariantInventoryService_.reserveQuantity( await this.productVariantInventoryService_.reserveQuantity(
+6 -5
View File
@@ -24,6 +24,7 @@ import { TaxProviderRepository } from "../repositories/tax-provider"
import { isCart } from "../types/cart" import { isCart } from "../types/cart"
import { TaxLinesMaps, TaxServiceRate } from "../types/tax-service" import { TaxLinesMaps, TaxServiceRate } from "../types/tax-service"
import TaxRateService from "./tax-rate" import TaxRateService from "./tax-rate"
import { promiseAll } from "@medusajs/utils"
type RegionDetails = { type RegionDetails = {
id: string id: string
@@ -101,7 +102,7 @@ class TaxProviderService extends TransactionBaseService {
this.smTaxLineRepo_ this.smTaxLineRepo_
) )
await Promise.all([ await promiseAll([
taxLineRepo.deleteForCart(cartId), taxLineRepo.deleteForCart(cartId),
shippingTaxRepo.deleteForCart(cartId), shippingTaxRepo.deleteForCart(cartId),
]) ])
@@ -153,7 +154,7 @@ class TaxProviderService extends TransactionBaseService {
) )
return ( return (
await Promise.all([ await promiseAll([
itemTaxLineRepo.upsertLines(lineItems), itemTaxLineRepo.upsertLines(lineItems),
shippingTaxLineRepo.upsertLines(shipping), shippingTaxLineRepo.upsertLines(shipping),
]) ])
@@ -281,7 +282,7 @@ class TaxProviderService extends TransactionBaseService {
} }
}) })
const shippingCalculationLines = await Promise.all( const shippingCalculationLines = await promiseAll(
calculationContext.shipping_methods.map(async (sm) => { calculationContext.shipping_methods.map(async (sm) => {
return { return {
shipping_method: sm, shipping_method: sm,
@@ -437,7 +438,7 @@ class TaxProviderService extends TransactionBaseService {
) )
const productRatesMapResult = new Map<string, TaxServiceRate[]>() const productRatesMapResult = new Map<string, TaxServiceRate[]>()
await Promise.all( await promiseAll(
[...cacheKeysMap].map(async ([id, cacheKey]) => { [...cacheKeysMap].map(async ([id, cacheKey]) => {
const cacheHit = await this.cacheService_.get<TaxServiceRate[]>( const cacheHit = await this.cacheService_.get<TaxServiceRate[]>(
cacheKey cacheKey
@@ -457,7 +458,7 @@ class TaxProviderService extends TransactionBaseService {
return productRatesMapResult return productRatesMapResult
} }
await Promise.all( await promiseAll(
nonCachedProductIds.map(async (id) => { nonCachedProductIds.map(async (id) => {
const rates = await this.taxRateService_ const rates = await this.taxRateService_
.withTransaction(this.activeManager_) .withTransaction(this.activeManager_)
+7 -6
View File
@@ -19,6 +19,7 @@ import {
} from "../types/tax-rate" } from "../types/tax-rate"
import { buildQuery, PostgresError } from "../utils" import { buildQuery, PostgresError } from "../utils"
import { TransactionBaseService } from "../interfaces" import { TransactionBaseService } from "../interfaces"
import { promiseAll } from "@medusajs/utils"
class TaxRateService extends TransactionBaseService { class TaxRateService extends TransactionBaseService {
protected readonly productService_: ProductService protected readonly productService_: ProductService
@@ -208,10 +209,10 @@ class TaxRateService extends TransactionBaseService {
async (err: any) => { async (err: any) => {
if (err.code === PostgresError.FOREIGN_KEY_ERROR) { if (err.code === PostgresError.FOREIGN_KEY_ERROR) {
// A foreign key constraint failed meaning some thing doesn't exist // A foreign key constraint failed meaning some thing doesn't exist
// either it is a product or the tax rate itself. Using Promise.all // either it is a product or the tax rate itself. Using promiseAll
// will try to retrieve all of the resources and will fail when // will try to retrieve all of the resources and will fail when
// something is not found. // something is not found.
await Promise.all([ await promiseAll([
this.retrieve(id, { select: ["id"] }), this.retrieve(id, { select: ["id"] }),
...ids.map(async (pId) => ...ids.map(async (pId) =>
this.productService_.retrieve(pId, { select: ["id"] }) this.productService_.retrieve(pId, { select: ["id"] })
@@ -244,10 +245,10 @@ class TaxRateService extends TransactionBaseService {
async (err: any) => { async (err: any) => {
if (err.code === PostgresError.FOREIGN_KEY_ERROR) { if (err.code === PostgresError.FOREIGN_KEY_ERROR) {
// A foreign key constraint failed meaning some thing doesn't exist // A foreign key constraint failed meaning some thing doesn't exist
// either it is a product or the tax rate itself. Using Promise.all // either it is a product or the tax rate itself. Using promiseAll
// will try to retrieve all of the resources and will fail when // will try to retrieve all of the resources and will fail when
// something is not found. // something is not found.
await Promise.all([ await promiseAll([
this.retrieve(id, { this.retrieve(id, {
select: ["id"], select: ["id"],
}) as Promise<unknown>, }) as Promise<unknown>,
@@ -297,10 +298,10 @@ class TaxRateService extends TransactionBaseService {
async (err: any) => { async (err: any) => {
if (err.code === PostgresError.FOREIGN_KEY_ERROR) { if (err.code === PostgresError.FOREIGN_KEY_ERROR) {
// A foreign key constraint failed meaning some thing doesn't exist // A foreign key constraint failed meaning some thing doesn't exist
// either it is a product or the tax rate itself. Using Promise.all // either it is a product or the tax rate itself. Using promiseAll
// will try to retrieve all of the resources and will fail when // will try to retrieve all of the resources and will fail when
// something is not found. // something is not found.
await Promise.all([ await promiseAll([
this.retrieve(id, { select: ["id"] }), this.retrieve(id, { select: ["id"] }),
...ids.map(async (sId) => ...ids.map(async (sId) =>
this.shippingOptionService_.retrieve(sId, { select: ["id"] }) this.shippingOptionService_.retrieve(sId, { select: ["id"] })
@@ -16,7 +16,7 @@ import {
TBuiltPriceListImportLine, TBuiltPriceListImportLine,
TParsedPriceListImportRowData, TParsedPriceListImportRowData,
} from "./types" } from "./types"
import { MedusaError, computerizeAmount } from "medusa-core-utils" import { computerizeAmount, MedusaError } from "medusa-core-utils"
import { BatchJob } from "../../../models" import { BatchJob } from "../../../models"
import { CreateBatchJobInput } from "../../../types/batch-job" import { CreateBatchJobInput } from "../../../types/batch-job"
@@ -24,6 +24,7 @@ import CsvParser from "../../../services/csv-parser"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { PriceListPriceCreateInput } from "../../../types/price-list" import { PriceListPriceCreateInput } from "../../../types/price-list"
import { TParsedProductImportRowData } from "../product/types" import { TParsedProductImportRowData } from "../product/types"
import { promiseAll } from "@medusajs/utils"
/* /*
* Default strategy class used for a batch import of products/variants. * Default strategy class used for a batch import of products/variants.
@@ -365,7 +366,7 @@ class PriceListImportStrategy extends AbstractBatchJobStrategy {
result: { files }, result: { files },
}) })
await Promise.all(uploadPromises) await promiseAll(uploadPromises)
} }
/** /**
@@ -2,7 +2,7 @@
import { computerizeAmount, MedusaError } from "medusa-core-utils" import { computerizeAmount, MedusaError } from "medusa-core-utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { AbstractBatchJobStrategy, IFileService } from "../../../interfaces" import { AbstractBatchJobStrategy, IFileService } from "../../../interfaces"
import ProductCategoryFeatureFlag from "../../../loaders/feature-flags/product-categories" import ProductCategoryFeatureFlag from "../../../loaders/feature-flags/product-categories"
import SalesChannelFeatureFlag from "../../../loaders/feature-flags/sales-channels" import SalesChannelFeatureFlag from "../../../loaders/feature-flags/sales-channels"
@@ -716,7 +716,7 @@ class ProductImportStrategy extends AbstractBatchJobStrategy {
result: { files }, result: { files },
}) })
await Promise.all(uploadPromises) await promiseAll(uploadPromises)
} }
/** /**
@@ -22,6 +22,7 @@ import IdempotencyKeyService from "../services/idempotency-key"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { RequestContext } from "../types/request" import { RequestContext } from "../types/request"
import SwapService from "../services/swap" import SwapService from "../services/swap"
import { promiseAll } from "@medusajs/utils"
type InjectedDependencies = { type InjectedDependencies = {
productVariantInventoryService: ProductVariantInventoryService productVariantInventoryService: ProductVariantInventoryService
@@ -260,7 +261,7 @@ class CartCompletionStrategy extends AbstractCartCompletionStrategy {
protected async removeReservations(reservations) { protected async removeReservations(reservations) {
if (this.inventoryService_) { if (this.inventoryService_) {
await Promise.all( await promiseAll(
reservations.map(async ([reservations]) => { reservations.map(async ([reservations]) => {
if (reservations) { if (reservations) {
return reservations.map(async (reservation) => { return reservations.map(async (reservation) => {
@@ -312,7 +313,7 @@ class CartCompletionStrategy extends AbstractCartCompletionStrategy {
const productVariantInventoryServiceTx = const productVariantInventoryServiceTx =
this.productVariantInventoryService_.withTransaction(manager) this.productVariantInventoryService_.withTransaction(manager)
reservations = await Promise.all( reservations = await promiseAll(
cart.items.map(async (item) => { cart.items.map(async (item) => {
if (item.variant_id) { if (item.variant_id) {
try { try {
@@ -6,8 +6,8 @@ import {
} from "../interfaces" } from "../interfaces"
import { ICacheService } from "@medusajs/types" import { ICacheService } from "@medusajs/types"
import { FlagRouter } from "@medusajs/utils" import { FlagRouter, promiseAll } from "@medusajs/utils"
import { MedusaError, isDefined } from "medusa-core-utils" import { isDefined } from "medusa-core-utils"
import { EntityManager } from "typeorm" import { EntityManager } from "typeorm"
import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing" import TaxInclusivePricingFeatureFlag from "../loaders/feature-flags/tax-inclusive-pricing"
import { MoneyAmountRepository } from "../repositories/money-amount" import { MoneyAmountRepository } from "../repositories/money-amount"
@@ -58,7 +58,7 @@ class PriceSelectionStrategy extends AbstractPriceSelectionStrategy {
const variantPricesMap = new Map<string, PriceSelectionResult>() const variantPricesMap = new Map<string, PriceSelectionResult>()
if (!context.ignore_cache) { if (!context.ignore_cache) {
const cacheHits = await Promise.all( const cacheHits = await promiseAll(
[...cacheKeysMap].map(async ([, cacheKey]) => { [...cacheKeysMap].map(async ([, cacheKey]) => {
return await this.cacheService_.get<PriceSelectionResult>(cacheKey) return await this.cacheService_.get<PriceSelectionResult>(cacheKey)
}) })
@@ -93,7 +93,7 @@ class PriceSelectionStrategy extends AbstractPriceSelectionStrategy {
results = await this.calculateVariantPrice_old(nonCachedData, context) results = await this.calculateVariantPrice_old(nonCachedData, context)
} }
await Promise.all( await promiseAll(
[...results].map(async ([variantId, prices]) => { [...results].map(async ([variantId, prices]) => {
variantPricesMap.set(variantId, prices) variantPricesMap.set(variantId, prices)
if (!context.ignore_cache) { if (!context.ignore_cache) {
@@ -284,7 +284,7 @@ class PriceSelectionStrategy extends AbstractPriceSelectionStrategy {
} }
public async onVariantsPricesUpdate(variantIds: string[]): Promise<void> { public async onVariantsPricesUpdate(variantIds: string[]): Promise<void> {
await Promise.all( await promiseAll(
variantIds.map( variantIds.map(
async (id: string) => await this.cacheService_.invalidate(`ps:${id}:*`) async (id: string) => await this.cacheService_.invalidate(`ps:${id}:*`)
) )
+1 -1
View File
@@ -34,7 +34,7 @@ class OrderSubscriber {
relations: ["discounts", "discounts.rule"], relations: ["discounts", "discounts.rule"],
}) })
await Promise.all( await promiseAll(
order.discounts.map(async (d) => { order.discounts.map(async (d) => {
const usageCount = d?.usage_count || 0 const usageCount = d?.usage_count || 0
return this.discountService_.update(d.id, { return this.discountService_.update(d.id, {
+3 -2
View File
@@ -1,3 +1,4 @@
import { promiseAll } from "@medusajs/utils"
import { flatten, groupBy, map, merge } from "lodash" import { flatten, groupBy, map, merge } from "lodash"
import { import {
EntityMetadata, EntityMetadata,
@@ -43,7 +44,7 @@ export async function queryEntityWithIds<T extends ObjectLiteral>({
) => false | undefined)[] ) => false | undefined)[]
}): Promise<T[]> { }): Promise<T[]> {
const alias = repository.metadata.name.toLowerCase() const alias = repository.metadata.name.toLowerCase()
return await Promise.all( return await promiseAll(
Object.entries(groupedRelations).map( Object.entries(groupedRelations).map(
async ([toplevel, topLevelRelations]) => { async ([toplevel, topLevelRelations]) => {
let querybuilder = repository.createQueryBuilder(alias) let querybuilder = repository.createQueryBuilder(alias)
@@ -191,7 +192,7 @@ export async function queryEntityWithoutRelations<T extends ObjectLiteral>({
let entities: T[] let entities: T[]
let count = 0 let count = 0
if (shouldCount) { if (shouldCount) {
const result = await Promise.all([qb.getMany(), qb.getCount()]) const result = await promiseAll([qb.getMany(), qb.getCount()])
entities = result[0] entities = result[0]
count = result[1] count = result[1]
} else { } else {
@@ -9,6 +9,7 @@ import {
import { isDate } from "lodash" import { isDate } from "lodash"
import { MedusaError } from "medusa-core-utils" import { MedusaError } from "medusa-core-utils"
import { validator } from "../validator" import { validator } from "../validator"
import { promiseAll } from "@medusajs/utils"
async function typeValidator( async function typeValidator(
typedClass: any, typedClass: any,
@@ -43,7 +44,7 @@ async function typeValidator(
if (isArray(typedClass) && isArray(plain)) { if (isArray(typedClass) && isArray(plain)) {
const errors: Map<any, string> = new Map() const errors: Map<any, string> = new Map()
const result = ( const result = (
await Promise.all( await promiseAll(
(plain as any[]).map( (plain as any[]).map(
async (p) => async (p) =>
await typeValidator(typedClass[0], p).catch((e) => { await typeValidator(typedClass[0], p).catch((e) => {
@@ -80,7 +81,7 @@ export function IsType(types: any[], validationOptions?: ValidationOptions) {
validator: { validator: {
async validate(value: unknown, args: ValidationArguments) { async validate(value: unknown, args: ValidationArguments) {
const errors: Map<any, string> = new Map() const errors: Map<any, string> = new Map()
const results = await Promise.all( const results = await promiseAll(
types.map( types.map(
async (v) => async (v) =>
await typeValidator(v, value).catch((e) => { await typeValidator(v, value).catch((e) => {
+5 -5
View File
@@ -4,7 +4,7 @@ import {
ModuleJoinerRelationship, ModuleJoinerRelationship,
} from "@medusajs/types" } from "@medusajs/types"
import { isObject, toPascalCase } from "@medusajs/utils" import { isObject, promiseAll, toPascalCase } from "@medusajs/utils"
import { MedusaModule } from "./medusa-module" import { MedusaModule } from "./medusa-module"
export type DeleteEntityInput = { export type DeleteEntityInput = {
@@ -311,10 +311,10 @@ export class RemoteLink {
deletePromises.push(...relatedServicesPromises) deletePromises.push(...relatedServicesPromises)
} }
await Promise.all(deletePromises) await promiseAll(deletePromises)
}) })
await Promise.all(servicePromises) await promiseAll(servicePromises)
return returnIdsList return returnIdsList
} }
@@ -376,7 +376,7 @@ export class RemoteLink {
promises.push(service.create(links)) promises.push(service.create(links))
} }
const created = await Promise.all(promises) const created = await promiseAll(promises)
return created.flat() return created.flat()
} }
@@ -424,7 +424,7 @@ export class RemoteLink {
promises.push(service.dismiss(links)) promises.push(service.dismiss(links))
} }
const created = await Promise.all(promises) const created = await promiseAll(promises)
return created.flat() return created.flat()
} }
@@ -12,6 +12,7 @@ import {
} from "./types" } from "./types"
import { EventEmitter } from "events" import { EventEmitter } from "events"
import { promiseAll } from "@medusajs/utils"
export type TransactionFlow = { export type TransactionFlow = {
modelId: string modelId: string
@@ -404,7 +405,7 @@ export class TransactionOrchestrator extends EventEmitter {
} }
} }
await Promise.all(execution) await promiseAll(execution)
if (nextSteps.next.length > 0) { if (nextSteps.next.length > 0) {
await this.executeNext(transaction) await this.executeNext(transaction)
+2 -2
View File
@@ -19,7 +19,7 @@ import {
WithRequiredProperty, WithRequiredProperty,
} from "@medusajs/types" } from "@medusajs/types"
import { SqlEntityManager } from "@mikro-orm/postgresql" import { SqlEntityManager } from "@mikro-orm/postgresql"
import { DALUtils, isDefined, MedusaError } from "@medusajs/utils" import { DALUtils, isDefined, MedusaError, promiseAll } from "@medusajs/utils"
import { ProductServiceTypes } from "../types/services" import { ProductServiceTypes } from "../types/services"
@@ -228,7 +228,7 @@ export class ProductRepository extends DALUtils.MikroOrmAbstractBaseRepository<P
productsToUpdate.map((product) => [product.id, product]) productsToUpdate.map((product) => [product.id, product])
) )
const products = await Promise.all( const products = await promiseAll(
data.map(async (updateData) => { data.map(async (updateData) => {
const product = productsToUpdateMap.get(updateData.id) const product = productsToUpdateMap.get(updateData.id)
@@ -61,6 +61,7 @@ import {
mapObjectTo, mapObjectTo,
MedusaContext, MedusaContext,
MedusaError, MedusaError,
promiseAll,
} from "@medusajs/utils" } from "@medusajs/utils"
import { import {
entityNameToLinkableKeysMap, entityNameToLinkableKeysMap,
@@ -734,7 +735,7 @@ export default class ProductModuleService<
ProductTypes.CreateProductOptionDTO[] ProductTypes.CreateProductOptionDTO[]
>() >()
const productsData = await Promise.all( const productsData = await promiseAll(
data.map(async (product) => { data.map(async (product) => {
const productData = { ...product } const productData = { ...product }
if (!productData.handle) { if (!productData.handle) {
@@ -816,7 +817,7 @@ export default class ProductModuleService<
}) })
} }
await Promise.all( await promiseAll(
[...productVariantsMap].map(async ([handle, variants]) => { [...productVariantsMap].map(async ([handle, variants]) => {
return await this.productVariantService_.create( return await this.productVariantService_.create(
productByHandleMap.get(handle)!, productByHandleMap.get(handle)!,
@@ -861,7 +862,7 @@ export default class ProductModuleService<
const productOptionsMap = new Map<string, TProductOption[]>() const productOptionsMap = new Map<string, TProductOption[]>()
const productsData = await Promise.all( const productsData = await promiseAll(
data.map(async (product) => { data.map(async (product) => {
const { variants, ...productData } = product const { variants, ...productData } = product
@@ -997,7 +998,7 @@ export default class ProductModuleService<
) )
} }
await Promise.all(promises) await promiseAll(promises)
return products return products
} }
@@ -0,0 +1,58 @@
import { promiseAll } from "../promise-all"
import { EOL } from "os"
describe("promiseAll", function () {
it("should throw an error if any of the promises throw", async function () {
const res = await promiseAll([
Promise.resolve(1),
(async () => {
throw new Error("error")
})(),
Promise.resolve(3),
]).catch((e) => e)
expect(res.message).toBe("error")
})
it("should throw errors if any of the promises throw and aggregate them", async function () {
const res = await promiseAll(
[
Promise.resolve(1),
(async () => {
throw new Error("error")
})(),
(async () => {
throw new Error("error2")
})(),
Promise.resolve(3),
],
{
aggregateErrors: true,
}
).catch((e) => e)
expect(res.message).toBe(["error", "error2"].join(EOL))
})
it("should return all values if all promises are fulfilled", async function () {
const res = await promiseAll([
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
])
expect(res).toEqual([1, 2, 3])
})
it("should return all values if all promises are fulfilled including waiting for nested promises", async function () {
const res = await promiseAll([
Promise.resolve(1),
(async () => {
await promiseAll([Promise.resolve(1), Promise.resolve(2)])
})(),
Promise.resolve(3),
])
expect(res).toEqual([1, undefined, 3])
})
})
+2 -1
View File
@@ -16,9 +16,10 @@ export * from "./map-object-to"
export * from "./medusa-container" export * from "./medusa-container"
export * from "./object-from-string-path" export * from "./object-from-string-path"
export * from "./object-to-string-path" export * from "./object-to-string-path"
export * from "./promise-all"
export * from "./remote-query-object-from-string" export * from "./remote-query-object-from-string"
export * from "./remote-query-object-to-string" export * from "./remote-query-object-to-string"
export * from './remove-nullisih' export * from "./remove-nullisih"
export * from "./set-metadata" export * from "./set-metadata"
export * from "./simple-hash" export * from "./simple-hash"
export * from "./string-to-select-relation-object" export * from "./string-to-select-relation-object"
+40
View File
@@ -0,0 +1,40 @@
import { EOL } from "os"
const getMessageError = (state: PromiseRejectedResult) =>
state.reason.message ?? state.reason
const isRejected = (
state: PromiseSettledResult<unknown>
): state is PromiseRejectedResult => {
return state.status === "rejected"
}
const getValue = (state: PromiseFulfilledResult<unknown>) => state.value
/**
* Promise.allSettled with error handling, safe alternative to Promise.all
* @param promises
* @param aggregateErrors
*/
export async function promiseAll<T extends readonly unknown[] | []>(
promises: T,
{ aggregateErrors } = { aggregateErrors: false }
): Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }> {
const states = await Promise.allSettled(promises)
const rejected = (states as PromiseSettledResult<unknown>[]).filter(
isRejected
)
if (rejected.length) {
if (aggregateErrors) {
throw new Error(rejected.map(getMessageError).join(EOL))
}
throw rejected[0].reason // Re throw the error itself
}
return (states as PromiseFulfilledResult<unknown>[]).map(
getValue
) as unknown as Promise<{ -readonly [P in keyof T]: Awaited<T[P]> }>
}
+4 -7
View File
@@ -3,14 +3,11 @@ import { NextFunction, Request, RequestHandler, Response } from "express"
type handler = (req: Request, res: Response) => Promise<void> type handler = (req: Request, res: Response) => Promise<void>
export const wrapHandler = (fn: handler): RequestHandler => { export const wrapHandler = (fn: handler): RequestHandler => {
return ( return (req: Request, res: Response, next: NextFunction) => {
req: Request & { errors?: Error[] }, const req_ = req as Request & { errors?: Error[] }
res: Response, if (req_?.errors?.length) {
next: NextFunction
) => {
if (req?.errors?.length) {
return res.status(400).json({ return res.status(400).json({
errors: req.errors, errors: req_.errors,
message: message:
"Provided request body contains errors. Please check the data and retry the request", "Provided request body contains errors. Please check the data and retry the request",
}) })
@@ -1,5 +1,6 @@
import { IInventoryService, InventoryItemDTO } from "@medusajs/types" import { IInventoryService, InventoryItemDTO } from "@medusajs/types"
import { WorkflowArguments } from "../../helper" import { WorkflowArguments } from "../../helper"
import { promiseAll } from "@medusajs/utils"
type Result = { type Result = {
tag: string tag: string
@@ -23,7 +24,7 @@ export async function createInventoryItems({
return void 0 return void 0
} }
return await Promise.all( return await promiseAll(
data.inventoryItems.map(async (item) => { data.inventoryItems.map(async (item) => {
const inventoryItem = await inventoryService!.createInventoryItem({ const inventoryItem = await inventoryService!.createInventoryItem({
sku: item.sku!, sku: item.sku!,
@@ -1,5 +1,6 @@
import { InventoryItemDTO } from "@medusajs/types" import { InventoryItemDTO } from "@medusajs/types"
import { WorkflowArguments } from "../../helper" import { WorkflowArguments } from "../../helper"
import { promiseAll } from "@medusajs/utils"
export async function detachInventoryItems({ export async function detachInventoryItems({
container, container,
@@ -21,7 +22,7 @@ export async function detachInventoryItems({
return [] return []
} }
await Promise.all( await promiseAll(
data.inventoryItems.map(async ({ tag, inventoryItem }) => { data.inventoryItems.map(async ({ tag, inventoryItem }) => {
return await productVariantInventoryService.detachInventoryItem( return await productVariantInventoryService.detachInventoryItem(
inventoryItem.id, inventoryItem.id,
@@ -1,4 +1,5 @@
import { WorkflowArguments } from "../../helper" import { WorkflowArguments } from "../../helper"
import { promiseAll } from "@medusajs/utils"
type ProductHandle = string type ProductHandle = string
type SalesChannelId = string type SalesChannelId = string
@@ -34,7 +35,7 @@ export async function attachSalesChannelToProducts({
} }
}) })
await Promise.all( await promiseAll(
Array.from(salesChannelIdProductIdsMap.entries()).map( Array.from(salesChannelIdProductIdsMap.entries()).map(
async ([salesChannelId, productIds]) => { async ([salesChannelId, productIds]) => {
return await salesChannelServiceTx.addProducts( return await salesChannelServiceTx.addProducts(
@@ -1,4 +1,5 @@
import { WorkflowArguments } from "../../helper" import { WorkflowArguments } from "../../helper"
import { promiseAll } from "@medusajs/utils"
type ProductHandle = string type ProductHandle = string
type ShippingProfileId = string type ShippingProfileId = string
@@ -33,7 +34,7 @@ export async function attachShippingProfileToProducts({
} }
}) })
await Promise.all( await promiseAll(
Array.from(profileIdProductIdsMap.entries()).map( Array.from(profileIdProductIdsMap.entries()).map(
async ([profileId, productIds]) => { async ([profileId, productIds]) => {
return await shippingProfileServiceTx.addProducts(profileId, productIds) return await shippingProfileServiceTx.addProducts(profileId, productIds)
@@ -1,4 +1,5 @@
import { WorkflowArguments } from "../../helper" import { WorkflowArguments } from "../../helper"
import { promiseAll } from "@medusajs/utils"
type ProductHandle = string type ProductHandle = string
type SalesChannelId = string type SalesChannelId = string
@@ -32,7 +33,7 @@ export async function detachSalesChannelFromProducts({
} }
}) })
await Promise.all( await promiseAll(
Array.from(salesChannelIdProductIdsMap.entries()).map( Array.from(salesChannelIdProductIdsMap.entries()).map(
async ([salesChannelId, productIds]) => { async ([salesChannelId, productIds]) => {
return await salesChannelServiceTx.removeProducts( return await salesChannelServiceTx.removeProducts(
@@ -1,4 +1,5 @@
import { WorkflowArguments } from "../../helper" import { WorkflowArguments } from "../../helper"
import { promiseAll } from "@medusajs/utils"
type ProductHandle = string type ProductHandle = string
type ShippingProfileId = string type ShippingProfileId = string
@@ -32,7 +33,7 @@ export async function detachShippingProfileFromProducts({
} }
}) })
await Promise.all( await promiseAll(
Array.from(profileIdProductIdsMap.entries()).map( Array.from(profileIdProductIdsMap.entries()).map(
async ([profileId, productIds]) => { async ([profileId, productIds]) => {
return await shippingProfileServiceTx.removeProducts( return await shippingProfileServiceTx.removeProducts(
+4
View File
@@ -35696,6 +35696,7 @@ __metadata:
"@babel/preset-env": ^7.7.5 "@babel/preset-env": ^7.7.5
"@babel/runtime": ^7.9.6 "@babel/runtime": ^7.9.6
"@medusajs/medusa": ^1.15.1 "@medusajs/medusa": ^1.15.1
"@medusajs/utils": "workspace:^"
axios: ^0.20.0 axios: ^0.20.0
body-parser: ^1.19.0 body-parser: ^1.19.0
client-sessions: ^0.8.0 client-sessions: ^0.8.0
@@ -35900,6 +35901,7 @@ __metadata:
"@babel/register": ^7.7.4 "@babel/register": ^7.7.4
"@babel/runtime": ^7.9.6 "@babel/runtime": ^7.9.6
"@medusajs/medusa": ^1.17.2 "@medusajs/medusa": ^1.17.2
"@medusajs/utils": "workspace:^"
axios: ^0.19.2 axios: ^0.19.2
axios-mock-adapter: ^1.18.2 axios-mock-adapter: ^1.18.2
axios-mock-server: ^0.19.1 axios-mock-server: ^0.19.1
@@ -35932,6 +35934,7 @@ __metadata:
"@babel/preset-env": ^7.7.5 "@babel/preset-env": ^7.7.5
"@babel/register": ^7.7.4 "@babel/register": ^7.7.4
"@babel/runtime": ^7.9.6 "@babel/runtime": ^7.9.6
"@medusajs/utils": "workspace:^"
body-parser: ^1.19.0 body-parser: ^1.19.0
client-sessions: ^0.8.0 client-sessions: ^0.8.0
contentful-management: ^5.27.1 contentful-management: ^5.27.1
@@ -36289,6 +36292,7 @@ __metadata:
"@babel/preset-env": ^7.15.6 "@babel/preset-env": ^7.15.6
"@babel/register": ^7.15.3 "@babel/register": ^7.15.3
"@babel/runtime": ^7.15.4 "@babel/runtime": ^7.15.4
"@medusajs/utils": "workspace:^"
"@shopify/shopify-api": ^1.4.1 "@shopify/shopify-api": ^1.4.1
axios: ^0.21.4 axios: ^0.21.4
body-parser: ^1.19.0 body-parser: ^1.19.0