feat: Add support for batch method for products and product variants (#7038)

* feat(products): Add batch methods for product and variants

* chore: Rename batch validator and minor changes based on PR review
This commit is contained in:
Stevche Radevski
2024-04-15 16:48:29 +02:00
committed by GitHub
parent c3efac5a0d
commit fd83e75e4b
25 changed files with 793 additions and 56 deletions
@@ -1,27 +1,48 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IPricingModuleService, PricingTypes } from "@medusajs/types"
import {
convertItemResponseToUpdateRequest,
MedusaError,
getSelectsAndRelationsFromObjectArray,
} from "@medusajs/utils"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
type UpdatePriceSetsStepInput = {
selector?: PricingTypes.FilterablePriceSetProps
update?: PricingTypes.UpdatePriceSetDTO
}
type UpdatePriceSetsStepInput =
| {
selector?: PricingTypes.FilterablePriceSetProps
update?: PricingTypes.UpdatePriceSetDTO
}
| {
price_sets: PricingTypes.UpsertPriceSetDTO[]
}
export const updatePriceSetsStepId = "update-price-sets"
export const updatePriceSetsStep = createStep(
updatePriceSetsStepId,
async (data: UpdatePriceSetsStepInput, { container }) => {
if (!data.selector || !data.update) {
return new StepResponse([], null)
}
const pricingModule = container.resolve<IPricingModuleService>(
ModuleRegistrationName.PRICING
)
if ("price_sets" in data) {
if (data.price_sets.some((p) => !p.id)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Price set id is required when doing a batch update"
)
}
const prevData = await pricingModule.list({
id: data.price_sets.map((p) => p.id) as string[],
})
const priceSets = await pricingModule.upsert(data.price_sets)
return new StepResponse(priceSets, prevData)
}
if (!data.selector || !data.update) {
return new StepResponse([], null)
}
const { selects, relations } = getSelectsAndRelationsFromObjectArray([
data.update,
])
@@ -36,27 +57,17 @@ export const updatePriceSetsStep = createStep(
data.update
)
return new StepResponse(updatedPriceSets, {
dataBeforeUpdate,
selects,
relations,
})
return new StepResponse(updatedPriceSets, dataBeforeUpdate)
},
async (revertInput, { container }) => {
if (!revertInput || !revertInput.dataBeforeUpdate?.length) {
return
}
const { dataBeforeUpdate, selects, relations } = revertInput
const pricingModule = container.resolve<IPricingModuleService>(
ModuleRegistrationName.PRICING
)
await pricingModule.upsert(
dataBeforeUpdate.map((data) =>
convertItemResponseToUpdateRequest(data, selects, relations)
)
)
if (!revertInput) {
return
}
await pricingModule.upsert(revertInput as PricingTypes.UpsertPriceSetDTO[])
}
)