-
Notifications
You must be signed in to change notification settings - Fork 1
/
command-bus.ts
85 lines (59 loc) · 1.75 KB
/
command-bus.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
interface Command {
}
interface CommandHandler {
handle(commmand: Command): any;
}
interface NextMiddleware {
executeNext(command: Command): any;
}
interface Middleware {
execute(command: Command, next: NextMiddleware): any;
}
interface CommandNameExtractor {
extract(command: Command): string;
}
interface HandlerLocator {
getHandlerForCommand(commandName: string): CommandHandler;
}
interface CommandBus {
handle(comand: Command): void;
}
class CommandHandlerMiddleware implements Middleware
{
constructor(readonly handlerLocator: HandlerLocator, readonly commandNameExtractor: CommandNameExtractor) {
}
execute(command: Command, next: NextMiddleware): any
{
let className: string = this.commandNameExtractor.extract(command);
return this.handlerLocator.getHandlerForCommand(className).handle(command);
}
}
class InMemoryCommandBus implements CommandBus {
readonly commands: Command[];
handle(command: Command): void {
this.commands.push(command);
}
}
class Commander implements CommandBus {
private middlewareChain;
constructor(readonly middlewares: Middleware[]) {
this.middlewareChain = this.createExcecutionChain(middlewares);
}
handle(command: Command): void {
this.middlewareChain.executeNext(command);
}
private createExcecutionChain(middlewares: Middleware[]): NextMiddleware {
let lastCallable: NextMiddleware = (new class implements NextMiddleware {
executeNext(command: Command): any {
}
});
for(let i: number = middlewares.length; i >= 0; i--) {
lastCallable = (new class implements NextMiddleware {
executeNext(command: Command): any {
return middlewares[i].execute(command, lastCallable);
}
});
}
return lastCallable;
}
}