Implement Commands

Factory commands

The main purpose of a factory command is to create a new instance of a root entity with initial values and then persist those changes to the database. Each factory command provides input data depending on what has been modelled in the Solution Designer before. As a return value, the factory command will automatically return the instance id of the created instance.

Here you can see an example implementation of a factory command, creating a new instance of root entity Order:

  /**
   * Factory command execution
   */
  public async execute(): Promise<void> {
    // Read input properties
    const { inputProperty1, inputProperty2 } = this.input;

    // create a new instance of the Root entity
    this.instance = this.factory.entity.Order();

    // fill properties of the instance using the values from the input
    this.instance.property1 = inputProperty1;
    this.instance.property2 = inputProperty2;

    // Set the instance property to an initial value
    this.instance.property3 = 'value3';

    // Save changes to the database
    await this.instance.persist();
  }

Instance commands

Instance commands usually hold logic to modify the state of a root entity instance and persist the updated state in the database. The instance that can be modified as well as the input of the command is provided automatically.

Here you can see an example implementation of an instance command, modifying an existing instance of root entity Order and throwing a business error if some special condition is met:

  /**
   * Instance command execution
   */
  public async execute(): Promise<void> {
    // get value from input
    const { newPropertyValue } = this.input;

    // Check current state of instance
    if (this.instance.property1 === 'SomeSpecialState'){
      // throw business error
      throw this.factory.error.nsacrnm.MyBusinessError(); 
    } else {
      // update property with new value
      this.instance.property1 = newPropertyValue;
    }

    // Save changes to the database
    await this.instance.persist();
  }

The deletion of a root entity should be also handled within an instance command:

  /**
   * Instance command deleting execution
   */
  public async execute(): Promise<void> {
    // Delete instance
    await this.instance.delete();
  }
Warning:

When deleting an instance, no persist call is needed to delete the instance from the database. Using delete() is sufficient.

Note:

If you are using the aggregate persistence functionality, please ensure that your code is compliant with the recommended restrictions of the used database. Consult MongoDB documentation for further information. For example: Because of the limitations of database operations and drivers, MongoDB does not recommend the use of timestamps, that are not within the year range of 0 - 9999, see Date and DateTime documentation.