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

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