Initialize with JavaScript or TypeScript
🚀 Installation​
Install the following packages by NPM command:
npm i sequential-workflow-model sequential-workflow-machine
🎬 Usage​
You can use the engine in a JavaScript or TypeScript application. We recommend to use TypeScript because a workflow uses a lot of data structures and it's hard to maintain data integrity.
At the beginning you need to define the type of your workflow definition.
import { Definition } from 'sequential-workflow-model';
interface MyDefinition extends Definition {
properties: {
verbose: boolean;
};
}
Next, define your step types.
import { Step } from 'sequential-workflow-model';
interface DownloadHtmlStep extends Step {
componentType: 'task';
type: 'downloadHtml';
properties: {
pageUrl: string;
};
}
// ...
Prepare the workflow definition.
const definition: MyDefinition = {
properties: {
verbose: true,
},
sequence: [
{
id: '0x00001',
componentType: 'task',
type: 'downloadHtml',
name: 'Download google.com',
properties: {
pageUrl: 'https://www.google.com',
},
},
],
};
Prepare the global state interface.
interface WorkflowGlobalState {
html: string | null;
}
Prepare activities for your steps. The engine supports multiple types of activities. The basic activity is the atom activity. It's a simple handler that executes an atomic step and updates the global state.
import { createAtomActivity } from 'sequential-workflow-machine';
interface DownloadHtmlStepState {
attempt: number;
}
const downloadHtmlActivity = createAtomActivity<DownloadHtmlStep, WorkflowGlobalState, DownloadHtmlStepState>('downloadHtml', {
init: () => ({
attempt: 0,
}),
handler: async (step: DownloadHtmlStep, globalState: WorkflowGlobalState, activityState: DownloadHtmlStepState) => {
globalState.html = await downloadHtml(step.properties.pageUrl);
activityState.attempt++;
},
});
Now we can create the activity set. The activity set is a collection of all supported activities.
import { createActivitySet } from 'sequential-workflow-machine';
const activitySet = createActivitySet<WorkflowGlobalState>([
downloadHtmlActivity,
]);
Finally, we can create the workflow machine and run it.
import { createWorkflowMachineBuilder } from 'sequential-workflow-machine';
const builder = createWorkflowMachineBuilder<WorkflowGlobalState>(activitySet);
const machine = builder.build(definition);
const interpreter = machine.create({
init: () => {
return {
html: null,
};
}
});
interpreter.onChange(() => { /* ... */ });
interpreter.onDone(() => { /* ... */ });
interpreter.start();
That's it!