Skip to content

Quick Start

Alex Chugaev edited this page Jan 10, 2021 · 2 revisions

This example demonstrates how to implement a complex save operation which includes 3 steps using CQRS.

Say, in order to perform save operation, we have to go through these steps:

  1. create attachments from the data list;
  2. save entity data (submit HTTP request with JSON payload);
  3. associate created attachments with the entity.

1. Register the CQRS module in the root module of your app

This allows access to such global services as EventBus, CommandBus, QueryBus, and ErrorBus.

import { NgModule } from '@angular/core';
import { CqrsModule } from '@ngry/cqrs';

@NgModule({
  imports: [
    CqrsModule.forRoot(),
  ]
})
export class AppModule {
}

2. Implement the feature module

Typically, the feature module is the one lazy-loaded when the user navigates to a certain route.

2.1. Declare feature-specific commands

export class PrepareAttachmentsCommand {
  constructor(
    readonly entity: Entity,
    readonly items: Array<Item>,
  ) {
  }
}
export class SaveEntityCommand {
  constructor(
    readonly entity: Entity,
    readonly attachments: Array<Attachment>,
  ) {
  }
}
export class AddAttachmentsCommand {
  constructor(
    readonly entity: Entity,
    readonly attachments: Array<Attachment>,
  ) {
  }
}

2.2. Declare feature-specific events

export class FormSubmitEvent {
  constructor(
    readonly entity: Entity,
    readonly attachments: Array<Attachment>,
  ) {
  }
}
export class PrepareAttachmentsDoneEvent {
  constructor(
    readonly entity: Entity,
    readonly attachments: Array<Attachment>,
  ) {
  }
}
export class SaveEntityDoneEvent {
  constructor(
    readonly entity: Entity,
    readonly attachments: Array<Attachment>,
  ) {
  }
}
export class SaveAttachmentsDoneEvent {
  constructor(
    readonly entity: Entity,
    readonly attachments: Array<Attachment>,
  ) {
  }
}

2.3. Register feature-specific command, event, query, error handlers and sagas in feature module

import { NgModule } from '@angular/core';
import { CqrsModule } from '@ngry/cqrs';

@NgModule({
  imports: [
    CqrsModule.forFeature({
      commands: [
        PrepareAttachmentsHandler,
        SaveEntityHandler,
        SaveAttachmentsHandler,
      ],
      events: [
        SavedHandler,
      ],
      sagas: [
        SaveSaga,
      ],
    }),
  ],
})
export class FeatureModule {
}