Skip to content

Commit

Permalink
feat(utils): Introduce promiseAll util (#5543)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrien2p authored Nov 8, 2023
1 parent e4ce2f4 commit f90ba02
Show file tree
Hide file tree
Showing 99 changed files with 464 additions and 297 deletions.
10 changes: 10 additions & 0 deletions .changeset/short-countries-agree.md
Original file line number Diff line number Diff line change
@@ -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
3 changes: 2 additions & 1 deletion packages/inventory/src/services/inventory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
InjectEntityManager,
MedusaContext,
MedusaError,
promiseAll,
} from "@medusajs/utils"
import { EntityManager } from "typeorm"
import { joinerConfig } from "../joiner-config"
Expand Down Expand Up @@ -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)
Expand Down
9 changes: 5 additions & 4 deletions packages/inventory/src/services/reservation-item.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
isDefined,
MedusaContext,
MedusaError,
promiseAll,
} from "@medusajs/utils"
import { EntityManager, FindManyOptions, In } from "typeorm"
import { InventoryLevelService } from "."
Expand Down Expand Up @@ -150,7 +151,7 @@ export default class ReservationItemService {
}))
)

const [newReservationItems] = await Promise.all([
const [newReservationItems] = await promiseAll([
reservationItemRepository.save(reservationItems),
...data.map(
async (data) =>
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions packages/medusa-fulfillment-webshipper/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions packages/medusa-plugin-brightpearl/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
23 changes: 11 additions & 12 deletions packages/medusa-plugin-brightpearl/src/services/brightpearl.js
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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,
},
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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[
Expand Down Expand Up @@ -355,9 +356,7 @@ class BrightpearlService extends BaseService {
}

const externallyReservedQuantityAdjustment =
bpinStock -
bpOnHand -
inventoryLevel.reserved_quantity
bpinStock - bpOnHand - inventoryLevel.reserved_quantity

if (externallyReservedQuantityAdjustment === 0) {
return
Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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)

Expand Down
1 change: 1 addition & 0 deletions packages/medusa-plugin-contentful/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion packages/medusa-plugin-contentful/src/services/contentful.js
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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) {
Expand Down
1 change: 1 addition & 0 deletions packages/medusa-source-shopify/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
8 changes: 4 additions & 4 deletions packages/medusa-source-shopify/src/services/shopify.js
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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)
})
)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
InventoryItemDTO,
InventoryLevelDTO,
} from "@medusajs/types"
import { promiseAll } from "@medusajs/utils"
import { LevelWithAvailability, ResponseInventoryItem } from "../../variants"

export const buildLevelsByInventoryItemId = (
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)),
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions packages/medusa/src/api/routes/admin/products/get-product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -114,7 +114,7 @@ export default async (req, res) => {
)
)
}
await Promise.all(decoratePromises)
await promiseAll(decoratePromises)

res.json({ product })
}
Expand Down
Loading

0 comments on commit f90ba02

Please sign in to comment.