feat: Implement missing methods in product module and make more tests pass (#6650)

The 2 bigger remaining tasks are:
1. handling prices for variants
2. Handling options (breaking change)

After that all tests should pass on both v1 and v2
This commit is contained in:
Stevche Radevski authored and GitHub committed 2024-03-11 11:03:24 +00:00
1 parent e124762873
commit ff4bd62f71
29 files changed
+1194 -321

No files matched your search

@@ -0,0 +1,30 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
export const createCollectionsStepId = "create-collections"
export const createCollectionsStep = createStep(
createCollectionsStepId,
async (data: ProductTypes.CreateProductCollectionDTO[], { container }) => {
const service = container.resolve<IProductModuleService>(
ModuleRegistrationName.PRODUCT
)
const created = await service.createCollections(data)
return new StepResponse(
created,
created.map((collection) => collection.id)
)
},
async (createdIds, { container }) => {
if (!createdIds?.length) {
return
}
const service = container.resolve<IProductModuleService>(
ModuleRegistrationName.PRODUCT
)
await service.deleteCollections(createdIds)
}
)
@@ -0,0 +1,27 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IProductModuleService } from "@medusajs/types"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
export const deleteCollectionsStepId = "delete-collections"
export const deleteCollectionsStep = createStep(
deleteCollectionsStepId,
async (ids: string[], { container }) => {
const service = container.resolve<IProductModuleService>(
ModuleRegistrationName.PRODUCT
)
await service.softDeleteCollections(ids)
return new StepResponse(void 0, ids)
},
async (prevIds, { container }) => {
if (!prevIds?.length) {
return
}
const service = container.resolve<IProductModuleService>(
ModuleRegistrationName.PRODUCT
)
await service.restoreCollections(prevIds)
}
)
@@ -7,3 +7,6 @@ export * from "./delete-product-options"
export * from "./create-product-variants"
export * from "./update-product-variants"
export * from "./delete-product-variants"
export * from "./create-collections"
export * from "./update-collections"
export * from "./delete-collections"
@@ -0,0 +1,49 @@
import { ModuleRegistrationName } from "@medusajs/modules-sdk"
import { IProductModuleService, ProductTypes } from "@medusajs/types"
import { getSelectsAndRelationsFromObjectArray } from "@medusajs/utils"
import { StepResponse, createStep } from "@medusajs/workflows-sdk"
type UpdateCollectionsStepInput = {
selector: ProductTypes.FilterableProductCollectionProps
update: ProductTypes.UpdateProductCollectionDTO
}
export const updateCollectionsStepId = "update-collections"
export const updateCollectionsStep = createStep(
updateCollectionsStepId,
async (data: UpdateCollectionsStepInput, { container }) => {
const service = container.resolve<IProductModuleService>(
ModuleRegistrationName.PRODUCT
)
const { selects, relations } = getSelectsAndRelationsFromObjectArray([
data.update,
])
const prevData = await service.listCollections(data.selector, {
select: selects,
relations,
})
const collections = await service.updateCollections(
data.selector,
data.update
)
return new StepResponse(collections, prevData)
},
async (prevData, { container }) => {
if (!prevData?.length) {
return
}
const service = container.resolve<IProductModuleService>(
ModuleRegistrationName.PRODUCT
)
await service.upsertCollections(
prevData.map((r) => ({
...(r as unknown as ProductTypes.UpdateProductCollectionDTO),
}))
)
}
)
@@ -0,0 +1,15 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk"
import { createCollectionsStep } from "../steps"
type WorkflowInput = { collections: ProductTypes.CreateProductCollectionDTO[] }
export const createCollectionsWorkflowId = "create-collections"
export const createCollectionsWorkflow = createWorkflow(
createCollectionsWorkflowId,
(
input: WorkflowData<WorkflowInput>
): WorkflowData<ProductTypes.ProductCollectionDTO[]> => {
return createCollectionsStep(input.collections)
}
)
@@ -0,0 +1,12 @@
import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk"
import { deleteCollectionsStep } from "../steps"
type WorkflowInput = { ids: string[] }
export const deleteCollectionsWorkflowId = "delete-collections"
export const deleteCollectionsWorkflow = createWorkflow(
deleteCollectionsWorkflowId,
(input: WorkflowData<WorkflowInput>): WorkflowData<void> => {
return deleteCollectionsStep(input.ids)
}
)
@@ -7,3 +7,6 @@ export * from "./update-product-options"
export * from "./create-product-variants"
export * from "./delete-product-variants"
export * from "./update-product-variants"
export * from "./create-collections"
export * from "./delete-collections"
export * from "./update-collections"
@@ -0,0 +1,20 @@
import { ProductTypes } from "@medusajs/types"
import { WorkflowData, createWorkflow } from "@medusajs/workflows-sdk"
import { updateCollectionsStep } from "../steps"
type UpdateCollectionsStepInput = {
selector: ProductTypes.FilterableProductCollectionProps
update: ProductTypes.UpdateProductCollectionDTO
}
type WorkflowInput = UpdateCollectionsStepInput
export const updateCollectionsWorkflowId = "update-collections"
export const updateCollectionsWorkflow = createWorkflow(
updateCollectionsWorkflowId,
(
input: WorkflowData<WorkflowInput>
): WorkflowData<ProductTypes.ProductCollectionDTO[]> => {
return updateCollectionsStep(input)
}
)
@@ -0,0 +1,71 @@
import {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "../../../../types/routing"
import {
deleteCollectionsWorkflow,
updateCollectionsWorkflow,
} from "@medusajs/core-flows"
import { UpdateProductCollectionDTO } from "@medusajs/types"
import { remoteQueryObjectFromString } from "@medusajs/utils"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
const remoteQuery = req.scope.resolve("remoteQuery")
const variables = { id: req.params.id }
const queryObject = remoteQueryObjectFromString({
entryPoint: "product_collection",
variables,
fields: req.retrieveConfig.select as string[],
})
const [collection] = await remoteQuery(queryObject)
res.status(200).json({ collection })
}
export const POST = async (
req: AuthenticatedMedusaRequest<UpdateProductCollectionDTO>,
res: MedusaResponse
) => {
const { result, errors } = await updateCollectionsWorkflow(req.scope).run({
input: {
selector: { id: req.params.id },
update: req.validatedBody,
},
throwOnError: false,
})
if (Array.isArray(errors) && errors[0]) {
throw errors[0].error
}
res.status(200).json({ collection: result[0] })
}
export const DELETE = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
const id = req.params.id
const { errors } = await deleteCollectionsWorkflow(req.scope).run({
input: { ids: [id] },
throwOnError: false,
})
if (Array.isArray(errors) && errors[0]) {
throw errors[0].error
}
res.status(200).json({
id,
object: "collection",
deleted: true,
})
}
@@ -0,0 +1,57 @@
import * as QueryConfig from "./query-config"
import {
AdminGetCollectionsCollectionParams,
AdminGetCollectionsParams,
AdminPostCollectionsCollectionReq,
AdminPostCollectionsReq,
} from "./validators"
import { transformBody, transformQuery } from "../../../api/middlewares"
import { MiddlewareRoute } from "../../../loaders/helpers/routing/types"
import { authenticate } from "../../../utils/authenticate-middleware"
export const adminCollectionRoutesMiddlewares: MiddlewareRoute[] = [
{
method: ["ALL"],
matcher: "/admin/collections*",
middlewares: [authenticate("admin", ["bearer", "session", "api-key"])],
},
{
method: ["GET"],
matcher: "/admin/collections",
middlewares: [
transformQuery(
AdminGetCollectionsParams,
QueryConfig.listTransformQueryConfig
),
],
},
{
method: ["GET"],
matcher: "/admin/collections/:id",
middlewares: [
transformQuery(
AdminGetCollectionsCollectionParams,
QueryConfig.retrieveTransformQueryConfig
),
],
},
{
method: ["POST"],
matcher: "/admin/collections",
middlewares: [transformBody(AdminPostCollectionsReq)],
},
{
method: ["POST"],
matcher: "/admin/collections/:id",
middlewares: [transformBody(AdminPostCollectionsCollectionReq)],
},
{
method: ["DELETE"],
matcher: "/admin/collections/:id",
middlewares: [],
},
// TODO: There were two batch methods, they need to be handled
]
@@ -0,0 +1,25 @@
export const allowedAdminCollectionRelations = ["products.profiles"]
// TODO: See how these should look when expanded
export const defaultAdminCollectionRelations = ["products.profiles"]
export const defaultAdminCollectionFields = [
"id",
"title",
"handle",
"created_at",
"updated_at",
]
export const retrieveTransformQueryConfig = {
defaultFields: defaultAdminCollectionFields,
defaultRelations: defaultAdminCollectionRelations,
allowedRelations: allowedAdminCollectionRelations,
isList: false,
}
export const listTransformQueryConfig = {
...retrieveTransformQueryConfig,
defaultLimit: 10,
isList: true,
}
@@ -0,0 +1,57 @@
import {
AuthenticatedMedusaRequest,
MedusaResponse,
} from "../../../types/routing"
import { CreateProductCollectionDTO } from "@medusajs/types"
import { createCollectionsWorkflow } from "@medusajs/core-flows"
import { remoteQueryObjectFromString } from "@medusajs/utils"
export const GET = async (
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) => {
const remoteQuery = req.scope.resolve("remoteQuery")
const queryObject = remoteQueryObjectFromString({
entryPoint: "product_collection",
variables: {
filters: req.filterableFields,
order: req.listConfig.order,
skip: req.listConfig.skip,
take: req.listConfig.take,
},
fields: req.listConfig.select as string[],
})
const { rows: collections, metadata } = await remoteQuery(queryObject)
res.json({
collections,
count: metadata.count,
offset: metadata.skip,
limit: metadata.take,
})
}
export const POST = async (
req: AuthenticatedMedusaRequest<CreateProductCollectionDTO>,
res: MedusaResponse
) => {
const input = [
{
...req.validatedBody,
},
]
const { result, errors } = await createCollectionsWorkflow(req.scope).run({
input: { collections: input },
throwOnError: false,
})
if (Array.isArray(errors) && errors[0]) {
throw errors[0].error
}
res.status(200).json({ collection: result[0] })
}
@@ -0,0 +1,115 @@
import { OperatorMap } from "@medusajs/types"
import { Type } from "class-transformer"
import {
IsNotEmpty,
IsObject,
IsOptional,
IsString,
ValidateNested,
} from "class-validator"
import { FindParams, extendedFindParamsMixin } from "../../../types/common"
import { OperatorMapValidator } from "../../../types/validators/operator-map"
// TODO: Ensure these match the DTOs in the types
export class AdminGetCollectionsCollectionParams extends FindParams {}
/**
* Parameters used to filter and configure the pagination of the retrieved regions.
*/
export class AdminGetCollectionsParams extends extendedFindParamsMixin({
limit: 10,
offset: 0,
}) {
/**
* Term to search product collections by their title and handle.
*/
@IsString()
@IsOptional()
q?: string
/**
* Title to filter product collections by.
*/
@IsOptional()
@IsString()
title?: string | string[]
/**
* Handle to filter product collections by.
*/
@IsOptional()
@IsString()
handle?: string | string[]
/**
* Date filters to apply on the product collections' `created_at` date.
*/
@IsOptional()
@ValidateNested()
@Type(() => OperatorMapValidator)
created_at?: OperatorMap<string>
/**
* Date filters to apply on the product collections' `updated_at` date.
*/
@IsOptional()
@ValidateNested()
@Type(() => OperatorMapValidator)
updated_at?: OperatorMap<string>
/**
* Date filters to apply on the product collections' `deleted_at` date.
*/
@ValidateNested()
@IsOptional()
@Type(() => OperatorMapValidator)
deleted_at?: OperatorMap<string>
// TODO: To be added in next iteration
// /**
// * Filter product collections by their associated discount condition's ID.
// */
// @IsString()
// @IsOptional()
// discount_condition_id?: string
// Note: These are new in v2
// Additional filters from BaseFilterable
@IsOptional()
@ValidateNested({ each: true })
@Type(() => AdminGetCollectionsParams)
$and?: AdminGetCollectionsParams[]
@IsOptional()
@ValidateNested({ each: true })
@Type(() => AdminGetCollectionsParams)
$or?: AdminGetCollectionsParams[]
}
export class AdminPostCollectionsReq {
@IsString()
@IsNotEmpty()
title: string
@IsString()
@IsOptional()
handle?: string
@IsObject()
@IsOptional()
metadata?: Record<string, unknown>
}
export class AdminPostCollectionsCollectionReq {
@IsString()
@IsOptional()
title?: string
@IsString()
@IsOptional()
handle?: string
@IsObject()
@IsOptional()
metadata?: Record<string, unknown>
}
@@ -39,9 +39,11 @@ export const POST = async (
req: AuthenticatedMedusaRequest<CreateProductOptionDTO>,
res: MedusaResponse
) => {
const productId = req.params.id
const input = [
{
...req.validatedBody,
product_id: productId,
},
]
@@ -24,13 +24,13 @@ export const GET = async (
const variables = { id: variantId, product_id: productId }
const queryObject = remoteQueryObjectFromString({
entryPoint: "product_variant",
entryPoint: "variant",
variables,
fields: req.retrieveConfig.select as string[],
})
const [product_variant] = await remoteQuery(queryObject)
res.status(200).json({ product_variant })
const [variant] = await remoteQuery(queryObject)
res.status(200).json({ variant })
}
export const POST = async (
@@ -55,7 +55,7 @@ export const POST = async (
throw errors[0].error
}
res.status(200).json({ product_variant: result[0] })
res.status(200).json({ variant: result[0] })
}
export const DELETE = async (
@@ -78,7 +78,7 @@ export const DELETE = async (
res.status(200).json({
id: variantId,
object: "product_variant",
object: "variant",
deleted: true,
})
}
@@ -15,7 +15,7 @@ export const GET = async (
const productId = req.params.id
const queryObject = remoteQueryObjectFromString({
entryPoint: "product_variant",
entryPoint: "variant",
variables: {
filters: { ...req.filterableFields, product_id: productId },
order: req.listConfig.order,
@@ -25,10 +25,10 @@ export const GET = async (
fields: req.listConfig.select as string[],
})
const { rows: product_variants, metadata } = await remoteQuery(queryObject)
const { rows: variants, metadata } = await remoteQuery(queryObject)
res.json({
product_variants,
variants,
count: metadata.count,
offset: metadata.skip,
limit: metadata.take,
@@ -39,9 +39,11 @@ export const POST = async (
req: AuthenticatedMedusaRequest<CreateProductVariantDTO>,
res: MedusaResponse
) => {
const productId = req.params.id
const input = [
{
...req.validatedBody,
product_id: productId,
},
]
@@ -56,5 +58,5 @@ export const POST = async (
throw errors[0].error
}
res.status(200).json({ product_variant: result[0] })
res.status(200).json({ variant: result[0] })
}
@@ -66,9 +66,9 @@ export const allowedAdminProductRelations = [
// TODO: See how this should be handled
// "options.values",
// TODO: Handle in next iteration
// "tags",
// "type",
// "collection",
"tags",
"type",
"collection",
]
// TODO: This is what we had in the v1 list. Do we still want to expand that much by default? Also this doesn't work in v2 it seems.
@@ -110,6 +110,12 @@ export const defaultAdminProductFields = [
"updated_at",
"deleted_at",
"metadata",
"type.id",
"type.value",
"type.metadata",
"type.created_at",
"type.updated_at",
"type.deleted_at",
"collection.id",
"collection.title",
"collection.handle",
@@ -17,7 +17,6 @@ import { OperatorMapValidator } from "../../../types/validators/operator-map"
import { ProductStatus } from "@medusajs/utils"
import { IsType } from "../../../utils"
import { optionalBooleanMapper } from "../../../utils/validators/is-boolean"
import { ProductTagReq, ProductTypeReq } from "../../../types/product"
export class AdminGetProductsProductParams extends FindParams {}
export class AdminGetProductsProductVariantsVariantParams extends FindParams {}
@@ -66,14 +65,6 @@ export class AdminGetProductsParams extends extendedFindParamsMixin({
@IsOptional()
handle?: string
// TODO: Should we remove this? It makes sense for search, but not for equality comparison
/**
* Description to filter products by.
*/
@IsString()
@IsOptional()
description?: string
/**
* Filter products by whether they're gift cards.
*/
@@ -402,11 +393,10 @@ export class AdminPostProductsProductReq {
@ValidateIf((_, value) => value !== undefined)
status?: ProductStatus
// TODO: Deal with in next iteration
// @IsOptional()
// @Type(() => ProductTypeReq)
// @ValidateNested()
// type?: ProductTypeReq
@IsOptional()
@Type(() => ProductTypeReq)
@ValidateNested()
type?: ProductTypeReq
@IsOptional()
@IsString()
@@ -432,12 +422,11 @@ export class AdminPostProductsProductReq {
// ])
// sales_channels?: ProductSalesChannelReq[] | null
// TODO: Should we remove this on update?
// @IsOptional()
// @Type(() => ProductVariantReq)
// @ValidateNested({ each: true })
// @IsArray()
// variants?: ProductVariantReq[]
@IsOptional()
@Type(() => ProductVariantReq)
@ValidateNested({ each: true })
@IsArray()
variants?: ProductVariantReq[]
@IsNumber()
@IsOptional()
@@ -544,11 +533,13 @@ export class AdminPostProductsProductVariantsReq {
@IsOptional()
metadata?: Record<string, unknown>
// TODO: Add on next iteration
// TODO: Add on next iteration, adding temporary field for now
// @IsArray()
// @ValidateNested({ each: true })
// @Type(() => ProductVariantPricesCreateReq)
// prices: ProductVariantPricesCreateReq[]
@IsArray()
prices: any[]
@IsOptional()
@IsObject()
@@ -651,3 +642,36 @@ export class AdminPostProductsProductOptionsOptionReq {
@IsArray()
values: string[]
}
// eslint-disable-next-line max-len
export class ProductVariantReq extends AdminPostProductsProductVariantsVariantReq {
@IsString()
id: string
}
export class ProductTagReq {
@IsString()
@IsOptional()
id?: string
@IsString()
value: string
}
/**
* The details of a product type, used to create or update an existing product type.
*/
export class ProductTypeReq {
/**
* The ID of the product type. It's only required when referring to an existing product type.
*/
@IsString()
@IsOptional()
id?: string
/**
* The value of the product type.
*/
@IsString()
value: string
}
@@ -1,6 +1,7 @@
import { MiddlewaresConfig } from "../loaders/helpers/routing/types"
import { adminApiKeyRoutesMiddlewares } from "./admin/api-keys/middlewares"
import { adminCampaignRoutesMiddlewares } from "./admin/campaigns/middlewares"
import { adminCollectionRoutesMiddlewares } from "./admin/collections/middlewares"
import { adminCurrencyRoutesMiddlewares } from "./admin/currencies/middlewares"
import { adminCustomerGroupRoutesMiddlewares } from "./admin/customer-groups/middlewares"
import { adminCustomerRoutesMiddlewares } from "./admin/customers/middlewares"
@@ -47,5 +48,6 @@ export const config: MiddlewaresConfig = {
...adminProductRoutesMiddlewares,
...adminPaymentRoutesMiddlewares,
...adminPriceListsRoutesMiddlewares,
...adminCollectionRoutesMiddlewares,
],
}
@@ -294,7 +294,7 @@ describe("ProductModuleService product collections", () => {
it("should emit events through event bus", async () => {
const eventBusSpy = jest.spyOn(EventBusService.prototype, "emit")
await service.updateCollections([
await service.upsertCollections([
{
id: collectionId,
title: "New Collection",
@@ -311,7 +311,7 @@ describe("ProductModuleService product collections", () => {
})
it("should update the value of the collection successfully", async () => {
await service.updateCollections([
await service.upsertCollections([
{
id: collectionId,
title: "New Collection",
@@ -324,7 +324,7 @@ describe("ProductModuleService product collections", () => {
})
it("should add products to a collection successfully", async () => {
await service.updateCollections([
await service.upsertCollections([
{
id: collectionId,
product_ids: [productOne.id, productTwo.id],
@@ -355,7 +355,7 @@ describe("ProductModuleService product collections", () => {
let error
try {
await service.updateCollections([
await service.upsertCollections([
{
id: "does-not-exist",
title: "New Collection",
@@ -18,6 +18,8 @@ import { buildProductAndRelationsData } from "../../../__fixtures__/product/data
import { DB_URL, TestDatabase, getInitModuleConfig } from "../../../utils"
import { UpdateProductInput } from "../../../../src/types/services/product"
jest.setTimeout(30000)
const beforeEach_ = async () => {
await TestDatabase.setupDatabase()
return await TestDatabase.forkManager()
+1 -1
View File
@@ -49,7 +49,7 @@ export const joinerConfig: ModuleJoinerConfig = {
},
},
{
name: ["variant", "variants"],
name: ["product_variant", "product_variants", "variant", "variants"],
args: {
entity: "ProductVariant",
methodSuffix: "Variants",
@@ -59,6 +59,7 @@ import {
ProductCategoryEvents,
} from "../types/services/product-category"
import { entityNameToLinkableKeysMap, joinerConfig } from "./../joiner-config"
import { UpdateCollectionInput } from "src/types/services/product-collection"
type InjectedDependencies = {
baseRepository: DAL.RepositoryService
@@ -459,19 +460,34 @@ export default class ProductModuleService<
>(productOptions)
}
@InjectTransactionManager("baseRepository_")
async createCollections(
createCollections(
data: ProductTypes.CreateProductCollectionDTO[],
sharedContext?: Context
): Promise<ProductTypes.ProductCollectionDTO[]>
createCollections(
data: ProductTypes.CreateProductCollectionDTO,
sharedContext?: Context
): Promise<ProductTypes.ProductCollectionDTO>
@InjectManager("baseRepository_")
async createCollections(
data:
| ProductTypes.CreateProductCollectionDTO[]
| ProductTypes.CreateProductCollectionDTO,
@MedusaContext() sharedContext: Context = {}
) {
const productCollections = await this.productCollectionService_.create(
data,
sharedContext
)
): Promise<
ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
> {
const input = Array.isArray(data) ? data : [data]
const collections = await this.createCollections_(input, sharedContext)
const createdCollections = await this.baseRepository_.serialize<
ProductTypes.ProductCollectionDTO[]
>(collections, { populate: true })
// eslint-disable-next-line max-len
await this.eventBusModuleService_?.emit<ProductCollectionServiceTypes.ProductCollectionEventData>(
productCollections.map(({ id }) => ({
collections.map(({ id }) => ({
eventName:
ProductCollectionServiceTypes.ProductCollectionEvents
.COLLECTION_CREATED,
@@ -479,22 +495,129 @@ export default class ProductModuleService<
}))
)
return JSON.parse(JSON.stringify(productCollections))
return Array.isArray(data) ? createdCollections : createdCollections[0]
}
@InjectTransactionManager("baseRepository_")
async updateCollections(
data: ProductTypes.UpdateProductCollectionDTO[],
async createCollections_(
data: ProductTypes.CreateProductCollectionDTO[],
@MedusaContext() sharedContext: Context = {}
): Promise<ProductTypes.ProductCollectionDTO[]> {
const productCollections = await this.productCollectionService_.update(
data,
): Promise<TProductCollection[]> {
return await this.productCollectionService_.create(data, sharedContext)
}
async upsertCollections(
data: ProductTypes.UpsertProductCollectionDTO[],
sharedContext?: Context
): Promise<ProductTypes.ProductCollectionDTO[]>
async upsertCollections(
data: ProductTypes.UpsertProductCollectionDTO,
sharedContext?: Context
): Promise<ProductTypes.ProductCollectionDTO>
@InjectTransactionManager("baseRepository_")
async upsertCollections(
data:
| ProductTypes.UpsertProductCollectionDTO[]
| ProductTypes.UpsertProductCollectionDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<
ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
> {
const input = Array.isArray(data) ? data : [data]
const forUpdate = input.filter(
(collection): collection is UpdateCollectionInput => !!collection.id
)
const forCreate = input.filter(
(collection): collection is ProductTypes.CreateProductCollectionDTO =>
!collection.id
)
let created: ProductCollection[] = []
let updated: ProductCollection[] = []
if (forCreate.length) {
created = await this.createCollections_(forCreate, sharedContext)
}
if (forUpdate.length) {
updated = await this.updateCollections_(forUpdate, sharedContext)
}
const result = [...created, ...updated]
const allCollections = await this.baseRepository_.serialize<
ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
>(Array.isArray(data) ? result : result[0])
if (created.length) {
await this.eventBusModuleService_?.emit<ProductCollectionServiceTypes.ProductCollectionEventData>(
created.map(({ id }) => ({
eventName:
ProductCollectionServiceTypes.ProductCollectionEvents
.COLLECTION_CREATED,
data: { id },
}))
)
}
if (updated.length) {
await this.eventBusModuleService_?.emit<ProductCollectionServiceTypes.ProductCollectionEventData>(
updated.map(({ id }) => ({
eventName:
ProductCollectionServiceTypes.ProductCollectionEvents
.COLLECTION_UPDATED,
data: { id },
}))
)
}
return Array.isArray(data) ? allCollections : allCollections[0]
}
updateCollections(
id: string,
data: ProductTypes.UpdateProductCollectionDTO,
sharedContext?: Context
): Promise<ProductTypes.ProductCollectionDTO>
updateCollections(
selector: ProductTypes.FilterableProductCollectionProps,
data: ProductTypes.UpdateProductCollectionDTO,
sharedContext?: Context
): Promise<ProductTypes.ProductCollectionDTO[]>
@InjectManager("baseRepository_")
async updateCollections(
idOrSelector: string | ProductTypes.FilterableProductCollectionProps,
data: ProductTypes.UpdateProductCollectionDTO,
@MedusaContext() sharedContext: Context = {}
): Promise<
ProductTypes.ProductCollectionDTO[] | ProductTypes.ProductCollectionDTO
> {
let normalizedInput: UpdateCollectionInput[] = []
if (isString(idOrSelector)) {
normalizedInput = [{ id: idOrSelector, ...data }]
} else {
const collections = await this.productCollectionService_.list(
idOrSelector,
{},
sharedContext
)
normalizedInput = collections.map((collection) => ({
id: collection.id,
...data,
}))
}
const collections = await this.updateCollections_(
normalizedInput,
sharedContext
)
// eslint-disable-next-line max-len
const updatedCollections = await this.baseRepository_.serialize<
ProductTypes.ProductCollectionDTO[]
>(collections)
await this.eventBusModuleService_?.emit<ProductCollectionServiceTypes.ProductCollectionEventData>(
productCollections.map(({ id }) => ({
updatedCollections.map(({ id }) => ({
eventName:
ProductCollectionServiceTypes.ProductCollectionEvents
.COLLECTION_UPDATED,
@@ -502,9 +625,15 @@ export default class ProductModuleService<
}))
)
return await this.baseRepository_.serialize(productCollections, {
populate: true,
})
return isString(idOrSelector) ? updatedCollections[0] : updatedCollections
}
@InjectTransactionManager("baseRepository_")
async updateCollections_(
data: UpdateCollectionInput[],
@MedusaContext() sharedContext: Context = {}
): Promise<TProductCollection[]> {
return await this.productCollectionService_.update(data, sharedContext)
}
@InjectTransactionManager("baseRepository_")
@@ -635,7 +764,7 @@ export default class ProductModuleService<
)
}
return allProducts
return Array.isArray(data) ? allProducts : allProducts[0]
}
update(
@@ -19,3 +19,7 @@ export type CreateProductCollection =
ProductTypes.CreateProductCollectionDTO & {
products?: string[]
}
export type UpdateCollectionInput = ProductTypes.UpdateProductCollectionDTO & {
id: string
}
+8 -5
View File
@@ -760,7 +760,7 @@ export interface FilterableProductCollectionProps
/**
* The title to filter product collections by.
*/
title?: string
title?: string | string[]
}
/**
@@ -872,16 +872,19 @@ export interface CreateProductCollectionDTO {
metadata?: Record<string, unknown>
}
export interface UpsertProductCollectionDTO extends UpdateProductCollectionDTO {
/**
* The ID of the product collection to update.
*/
id?: string
}
/**
* @interface
*
* The data to update in a product collection. The `id` is used to identify which product collection to update.
*/
export interface UpdateProductCollectionDTO {
/**
* The ID of the product collection to update.
*/
id: string
/**
* The value of the product collection.
*/
+197 -11
View File
@@ -28,6 +28,7 @@ import {
UpdateProductTagDTO,
UpdateProductTypeDTO,
UpdateProductVariantDTO,
UpsertProductCollectionDTO,
UpsertProductDTO,
} from "./common"
@@ -2086,7 +2087,7 @@ export interface IProductModuleService extends IModuleService {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function createCollection (title: string) {
* async function createCollections (title: string) {
* const productModule = await initializeProductModule()
*
* const collections = await productModule.createCollections([
@@ -2105,11 +2106,100 @@ export interface IProductModuleService extends IModuleService {
): Promise<ProductCollectionDTO[]>
/**
* This method is used to update existing product collections.
* This method is used to create a product collection.
*
* @param {UpdateProductCollectionDTO[]} data - The product collections to be updated, each holding the attributes that should be updated in the product collection.
* @param {CreateProductCollectionDTO} data - The product collection to be created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductCollectionDTO[]>} The list of updated product collections.
* @returns {Promise<ProductCollectionDTO>} The created product collection.
*
* @example
* import {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function createCollection (title: string) {
* const productModule = await initializeProductModule()
*
* const collection = await productModule.createCollections(
* {
* title
* }
* )
*
* // do something with the product collection or return them
* }
*
*/
createCollections(
data: CreateProductCollectionDTO,
sharedContext?: Context
): Promise<ProductCollectionDTO>
/**
* This method updates existing collections, or creates new ones if they don't exist.
*
* @param {UpsertProductCollectionDTO[]} data - The attributes to update or create for each collection.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductCollectionDTO[]>} The updated and created collections.
*
* @example
* import {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function upserCollections (title: string) {
* const productModule = await initializeProductModule()
*
* const createdCollections = await productModule.upsert([
* {
* title
* }
* ])
*
* // do something with the collections or return them
* }
*/
upsertCollections(
data: UpsertProductCollectionDTO[],
sharedContext?: Context
): Promise<ProductCollectionDTO[]>
/**
* This method updates an existing collection, or creates a new one if it doesn't exist.
*
* @param {UpsertProductCollectionDTO} data - The attributes to update or create for the collection.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductCollectionDTO>} The updated or created collection.
*
* @example
* import {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function upserCollection (title: string) {
* const productModule = await initializeProductModule()
*
* const createdCollection = await productModule.upsert(
* {
* title
* }
* )
*
* // do something with the collection or return it
* }
*/
upsertCollections(
data: UpsertProductCollectionDTO,
sharedContext?: Context
): Promise<ProductCollectionDTO>
/**
* This method is used to update a collection.
*
* @param {string} id - The ID of the collection to be updated.
* @param {UpdateProductCollectionDTO} data - The attributes of the collection to be updated
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductCollectionDTO>} The updated collection.
*
* @example
* import {
@@ -2119,19 +2209,47 @@ export interface IProductModuleService extends IModuleService {
* async function updateCollection (id: string, title: string) {
* const productModule = await initializeProductModule()
*
* const collections = await productModule.updateCollections([
* {
* id,
* const collection = await productModule.updateCollections(id, {
* title
* }
* ])
* )
*
* // do something with the product collections or return them
* // do something with the collection or return it
* }
*
*/
updateCollections(
data: UpdateProductCollectionDTO[],
id: string,
data: UpdateProductCollectionDTO,
sharedContext?: Context
): Promise<ProductCollectionDTO>
/**
* This method is used to update a list of collections determined by the selector filters.
*
* @param {FilterableProductCollectionProps} selector - The filters that will determine which collections will be updated.
* @param {UpdateProductCollectionDTO} data - The attributes to be updated on the selected collections
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<ProductCollectionDTO[]>} The updated collections.
*
* @example
* import {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function updateCollections(ids: string[], title: string) {
* const productModule = await initializeProductModule()
*
* const collections = await productModule.updateCollections({id: ids}, {
* title
* }
* )
*
* // do something with the collections or return them
* }
*/
updateCollections(
selector: FilterableProductCollectionProps,
data: UpdateProductCollectionDTO,
sharedContext?: Context
): Promise<ProductCollectionDTO[]>
@@ -2761,6 +2879,74 @@ export interface IProductModuleService extends IModuleService {
sharedContext?: Context
): Promise<Record<string, string[]> | void>
/**
* This method is used to delete product collections. Unlike the {@link deleteCollections} method, this method won't completely remove the collection. It can still be accessed or retrieved using methods like {@link retrieveCollections} if you pass the `withDeleted` property to the `config` object parameter.
*
* The soft-deleted collections can be restored using the {@link restoreCollections} method.
*
* @param {string[]} collectionIds - The IDs of the collections to soft-delete.
* @param {SoftDeleteReturn<TReturnableLinkableKeys>} config -
* Configurations determining which relations to soft delete along with the each of the collections. You can pass to its `returnLinkableKeys`
* property any of the collection's relation attribute names.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<Record<string, string[]> | void>}
* An object that includes the IDs of related records that were also soft deleted. The object's keys are the ID attribute names of the collection entity's relations.
*
* If there are no related records, the promise resolved to `void`.
*
* @example
* import {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function deleteCollections (ids: string[]) {
* const productModule = await initializeProductModule()
*
* const cascadedEntities = await productModule.softDeleteCollections(ids)
*
* // do something with the returned cascaded entity IDs or return them
* }
*/
softDeleteCollections<TReturnableLinkableKeys extends string = string>(
collectionIds: string[],
config?: SoftDeleteReturn<TReturnableLinkableKeys>,
sharedContext?: Context
): Promise<Record<string, string[]> | void>
/**
* This method is used to restore collections which were deleted using the {@link softDelete} method.
*
* @param {string[]} collectionIds - The IDs of the collections to restore.
* @param {RestoreReturn<TReturnableLinkableKeys>} config -
* Configurations determining which relations to restore along with each of the collections. You can pass to its `returnLinkableKeys`
* property any of the collection's relation attribute names.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<Record<string, string[]> | void>}
* An object that includes the IDs of related records that were restored. The object's keys are the ID attribute names of the product entity's relations.
*
* If there are no related records that were restored, the promise resolved to `void`.
*
* @example
* import {
* initialize as initializeProductModule,
* } from "@medusajs/product"
*
* async function restoreCollections (ids: string[]) {
* const productModule = await initializeProductModule()
*
* const cascadedEntities = await productModule.restoreCollections(ids, {
* returnLinkableKeys: []
* })
*
* // do something with the returned cascaded entity IDs or return them
* }
*/
restoreCollections<TReturnableLinkableKeys extends string = string>(
collectionIds: string[],
config?: RestoreReturn<TReturnableLinkableKeys>,
sharedContext?: Context
): Promise<Record<string, string[]> | void>
/**
* This method is used to restore product varaints that were soft deleted. Product variants are soft deleted when they're not
* provided in a product's details passed to the {@link update} method.