-
Notifications
You must be signed in to change notification settings - Fork 238
/
Copy pathprocessInboundMessageCommand.handler.ts
64 lines (54 loc) · 2.12 KB
/
processInboundMessageCommand.handler.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
import { CommandHandler, ICommandHandler } from '@nestjs/cqrs';
import { AuthAgent } from '../../../auth/agent/auth.agent';
import { BpiMessageAgent } from '../../agents/bpiMessages.agent';
import { BpiMessageStorageAgent } from '../../agents/bpiMessagesStorage.agent';
import { MessagingAgent } from '../../agents/messaging.agent';
import { ProcessInboundBpiMessageCommand } from './processInboundMessage.command';
// Difference between this and the create bpi message command handler is that this one does not
// stop the execution flow by throwing a nestjs exception (which results in 404 response in the other handler)
// TODO: Consider using a NestJs Saga or another command dispatch to avoid code duplication
@CommandHandler(ProcessInboundBpiMessageCommand)
export class ProcessInboundMessageCommandHandler
implements ICommandHandler<ProcessInboundBpiMessageCommand>
{
constructor(
private readonly agent: BpiMessageAgent,
private readonly storageAgent: BpiMessageStorageAgent,
private readonly messagingAgent: MessagingAgent,
private readonly authAgent: AuthAgent,
) {}
async execute(command: ProcessInboundBpiMessageCommand) {
if (await this.agent.bpiMessageIdAlreadyExists(command.id)) {
return false;
}
const [fromBpiSubject, toBpiSubject] =
await this.agent.fetchFromAndToBpiSubjects(command.from, command.to);
if (!fromBpiSubject || !toBpiSubject) {
return false;
}
const isSignatureValid = this.authAgent.verifySignatureAgainstPublicKey(
command.content,
command.signature,
fromBpiSubject.publicKeys[0].value,
);
if (!isSignatureValid) {
return false;
}
const newBpiMessageCandidate = this.agent.createNewBpiMessage(
command.id,
fromBpiSubject,
toBpiSubject,
command.content,
command.signature,
command.type,
);
const newBpiMessage = await this.storageAgent.storeNewBpiMessage(
newBpiMessageCandidate,
);
await this.messagingAgent.publishMessage(
toBpiSubject.publicKeys[0].value,
this.messagingAgent.serializeBpiMessage(newBpiMessage),
);
return true;
}
}