UNPKG

1.89 kBJavaScriptView Raw
1'use strict';
2
3const uuid = require('uuid/v4');
4const formats = require('formats');
5
6const MESSAGE_TYPE = 'command';
7
8class Command {
9 constructor({
10 id,
11 context,
12 aggregate,
13 name,
14 payload = {},
15 metadata = {},
16 }) {
17 if (!formats.isAlphanumeric(context, { minLength: 1 }))
18 throw new Error('Invalid context.');
19
20 if (!formats.isObject(aggregate))
21 throw new Error('Invalid aggregate.');
22
23 if (!formats.isAlphanumeric(aggregate.name, { minLength: 1 }))
24 throw new Error('Aggregate name is missing.');
25
26 if (!formats.isString(name, { minLength: 1 }))
27 throw new Error('Command name is missing.');
28
29 if (!formats.isObject(payload))
30 throw new Error('Payload must be an object.');
31
32 if (!formats.isObject(metadata))
33 throw new Error('Metadata must be an object.');
34
35 this.context = context;
36 this.aggregate = { name: aggregate.name, id: aggregate.id, revision: aggregate.revision };
37 this.name = name;
38
39 this.id = id || uuid();
40
41 this.metadata = {
42 ...metadata,
43 causationId: metadata.causationId || this.id,
44 timestamp: (new Date()).getTime(),
45 };
46
47 this.payload = payload;
48 this.routingKey = 'command';// .${this.context}.${this.aggregate.name}`;
49 }
50
51 serialize() {
52 return JSON.parse(JSON.stringify(this));
53 }
54
55 get messageType() { // eslint-disable-line
56 return MESSAGE_TYPE;
57 }
58
59 get fullname() {
60 return `${this.context}.${this.aggregate.name}.${this.name}`;
61 }
62
63 static deserialize({
64 id,
65 context,
66 aggregate,
67 name,
68 payload = {},
69 metadata = {},
70 }) {
71 return new Command({
72 id,
73 context,
74 aggregate,
75 name,
76 payload,
77 metadata,
78 });
79 }
80
81 static definition() {
82 return {
83 id: 'id',
84 context: 'context',
85 // aggregate
86 aggregateId: 'aggregate.id',
87 aggregate: 'aggregate.name',
88 revision: 'aggregate.revision',
89
90 name: 'name',
91 payload: 'payload',
92
93 meta: 'metadata',
94 };
95 }
96}
97
98module.exports = Command;