-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandBus.js
52 lines (49 loc) · 1.68 KB
/
CommandBus.js
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
import { SUFFIX_AFTER_HANDLE, SUFFIX_BEFORE_HANDLE } from './constants.js';
import BusExceptionEvent from './events/BusExceptionEvent.js';
import PbjxEvent from './events/PbjxEvent.js';
export default class CommandBus {
/**
* @param {ServiceLocator} locator
* @param {Transport} transport
*/
constructor(locator, transport) {
Object.defineProperty(this, 'locator', { value: locator });
Object.defineProperty(this, 'transport', { value: transport });
}
/**
* Processes a command asynchronously.
*
* @param {Message} command - Expected to be a message using mixin 'gdbots:pbjx:mixin:command'
*
* @returns {Promise}
*/
async send(command) {
return this.transport.sendCommand(command.freeze());
}
/**
* Invokes the handler that services the given command. If an exception occurs
* it will be processed by the exception handler and rethrown.
*
* @internal
* @package
*
* @param {Message} command - Expected to be a message using mixin 'gdbots:pbjx:mixin:command'
*
* @returns {Promise}
*/
async receiveCommand(command) {
try {
const handler = await this.locator.getCommandHandler(command.schema().getCurie());
command.freeze();
const pbjx = await this.locator.getPbjx();
const event = new PbjxEvent(command);
await pbjx.trigger(command, SUFFIX_BEFORE_HANDLE, event, false);
await handler.handleCommand(command, pbjx);
await pbjx.trigger(command, SUFFIX_AFTER_HANDLE, event, false);
} catch (e) {
const exceptionHandler = await this.locator.getExceptionHandler();
await exceptionHandler.onCommandBusException(new BusExceptionEvent(command, e));
throw e;
}
}
}