diff --git a/packages/core/orchestration/src/transaction/orchestrator-builder.ts b/packages/core/orchestration/src/transaction/orchestrator-builder.ts index 227107caa7..3bdbe5d981 100644 --- a/packages/core/orchestration/src/transaction/orchestrator-builder.ts +++ b/packages/core/orchestration/src/transaction/orchestrator-builder.ts @@ -22,9 +22,11 @@ export class OrchestratorBuilder { this.steps = { depth: -1, parent: null, - next: steps + next: Object.keys(steps ?? {}).length ? JSON.parse( - JSON.stringify((steps.action ? steps : steps.next) as InternalStep) + JSON.stringify( + (steps!.action ? steps : steps!.next) as InternalStep + ) ) : undefined, } diff --git a/packages/core/workflows-sdk/src/utils/composer/__tests__/index.spec.ts b/packages/core/workflows-sdk/src/utils/composer/__tests__/index.spec.ts index d2a5f989ac..fda0482469 100644 --- a/packages/core/workflows-sdk/src/utils/composer/__tests__/index.spec.ts +++ b/packages/core/workflows-sdk/src/utils/composer/__tests__/index.spec.ts @@ -134,6 +134,33 @@ describe("Workflow composer", () => { expect(res2).toEqual({ result: "default response" }) }) + it("should not return value if when condition is false", async function () { + const workflow = createWorkflow( + getNewWorkflowId(), + function (input: { ret: boolean }) { + const value = when({ input }, ({ input }) => { + return input.ret + }).then(() => { + return { hasValue: true } + }) + + return new WorkflowResponse(value) + } + ) + + const { result } = await workflow.run({ + input: { ret: false }, + }) + + expect(result).toEqual(undefined) + + const { result: res2 } = await workflow.run({ + input: { ret: true }, + }) + + expect(res2).toEqual({ hasValue: true }) + }) + it("should revert the workflow and sub workflow on failure", async function () { const step1Mock = jest.fn() const step1 = createStep( diff --git a/packages/core/workflows-sdk/src/utils/composer/when.ts b/packages/core/workflows-sdk/src/utils/composer/when.ts index ebbfe0dbe7..fdb3f70959 100644 --- a/packages/core/workflows-sdk/src/utils/composer/when.ts +++ b/packages/core/workflows-sdk/src/utils/composer/when.ts @@ -1,4 +1,7 @@ import { OrchestrationUtils } from "@medusajs/utils" +import { ulid } from "ulid" +import { createStep } from "./create-step" +import { StepResponse } from "./helpers/step-response" import { StepExecutionContext, WorkflowData } from "./type" type ConditionFunction = ( @@ -41,17 +44,26 @@ export function when(input, condition) { then: (fn) => { thenCalled = true const ret = fn() + let returnStep = ret const applyCondition = global[OrchestrationUtils.SymbolMedusaWorkflowComposerCondition].steps + if (ret?.__type !== OrchestrationUtils.SymbolWorkflowStep) { + const retStep = createStep( + "when-then-" + ulid(), + () => new StepResponse(ret) + ) + returnStep = retStep() + } + for (const step of applyCondition) { step.if(input, condition) } delete global[OrchestrationUtils.SymbolMedusaWorkflowComposerCondition] - return ret + return returnStep }, } }