Building It Step By StepWorkflow to JSON

Building It Step By Step

Workflow to JSON

Learn how to convert workflows into JSON format so they can be stored in databases.


Getting Started

Navigate to the corresponding folder:

cd step-8-workflow-to-json

Install the dependencies:

npm install

Then run the project:

npm run dev

Workflow to JSON

To convert the workflow to a JSON format, we first need the corresponding JSON type, which can be found in the file shown below.

// src/shared/kits/workflow/types/workflow-schema.ts

export type WorkflowSchema = {
  start: { message: string };
  elements: ElementSchema[];
  end: { message: string };
};

// ...

To convert the workflow into this JSON format, we use the function shown below.

// src/shared/kits/workflow/utilities/to-workflow-schema.ts

// ...

export function toWorkflowSchema(workflow: Workflow): WorkflowSchema {
  return {
    start: { message: workflow.flow.start.message },
    elements: workflow.flow.elements.map((element) => elementToSchema(element)),
    end: { message: workflow.flow.end.message },
  };
}

// ...

To convert the JSON format back into the workflow, we use the function shown below.

// src/shared/kits/workflow/utilities/to-workflow.ts

// ...

export function toWorkflow(schema: WorkflowSchema): Workflow {
  return {
    flow: {
      start: { message: schema.start.message },
      dropTop: new Set<string>(),
      elements: schema.elements.map((element) => elementToWorkflow(element)),
      end: { message: schema.end.message },
    },
    widget: null,
    active: null,
    failure: null,
  };
}

// ...