Skip to content

Commit d0eaa82

Browse files
committed
Initial implementation
1 parent 9a65a43 commit d0eaa82

1 file changed

Lines changed: 85 additions & 0 deletions

File tree

command-bus.ts

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

0 commit comments

Comments
 (0)