Skip to content
This repository was archived by the owner on Jan 10, 2019. It is now read-only.

mutm/angular-command-bus

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Angular command bus

Implementation command bus pattern with the support middleware as Angular module

Installation

npm install angular-command-bus --save

Configuration

Module
@NgModule({
  imports: [
      CommandBusModule.forRoot()
  ]
})
export class AppModule {
}

Example

Model
export class Order {
    constructor(private id: string, private name: string) {}
}
Command
export class CreateOrderCommand {
    constructor(readonly orderId: string, readonly name: string) {}
}
Handler
export class CreateOrderHandler implements CommandHandler {
    constructor(orderService: OrderService) {}
    
    handle(command: CreateOrderCommand) {
        const order = new Order(command.orderId, command.name);
        orderService.save(order);
    }
    
    supportsCommand(): string {
        return CreateOrderCommand.name;
    }
}
Component
@Component({
  selector: 'app-orders-page',
  templateUrl: './orders-page.component.html',
  styleUrls: ['./orders-page.component.scss']
})
export class OrdersPageComponent {
    constructor(private commandBus: CommandBus) {}
    
    onSubmit() {
        this.commandBus.handle(new CreateOrderCommand(id, name));
    }
}

Adding middleware

This is a kind of pattern Intercepting filter from Core J2EE Patterns

@NgModule({
  providers: [
      {provide: COMMAND_BUS_MIDDLEWARE, useClass: LoggingMiddleware, multi: true},
      {provide: COMMAND_BUS_MIDDLEWARE, useClass: AuthorizationMiddleware, multi: true}
  ]
})
export class AppModule {
}
Middleware class
export class LoggingMiddleware implements CommandBusMiddleware {
    /*
     * @param next this is a reference for next middleware function
     */
    handle(command, next) {
        // before code
        next(command);
        // after code
    }
}

if 'next' is not called, the processing of the command will be completed and further middleware, as well as the command handler, will not be executed.

For example AuthorizationMiddleware

export class AuthorizationMiddleware implements CommandBusMiddleware {
    constructor(
        private userService: UserService,
        private notificationService: NotificationService
    ) {}
    
    handle(command, next) {
        if (!userService.hasRole('ROLE_ADMIN')) {
            notificationService.alert(
                'Access denied for handle command ' + command.constructor.name
            );
            return;
        }
        
        next(command);
    }
}

About

Angular command bus module

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published