-
Notifications
You must be signed in to change notification settings - Fork 0
/
mydomain.js
121 lines (104 loc) · 2.09 KB
/
mydomain.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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import { map } from "rxjs";
import { Domain, AggregateRoot } from "../src/index.js";
class ItemRepository {
/**@type {Domain}*/
domain;
constructor(domain) {
this.domain = domain;
}
#itemMap = new Map();
all() {
return [...this.#itemMap.values()];
}
get(id) {
return this.#itemMap.get(id);
}
remove(id) {
this.#itemMap.delete(id);
}
num = 0;
create() {
++this.num;
const ItemClass = this.domain.getAggegateClass(Item);
const item = new ItemClass("id" + this.num);
this.#itemMap.set(item.id, item);
const event = {
type: "create item",
};
this.domain.eventBus.publish(event);
return item;
}
}
class MyDomain extends Domain {
itemRepository = new ItemRepository(this);
}
// const { name: string, type: "change item name" };
// { type: "create item" };
// {type: "done"}
class Item extends AggregateRoot {
/**
*
* @param {string} id
*/
constructor(id) {
super();
}
#name = "";
get name() {
return this.#name;
}
changeName(name) {
const changeNameEvent = {
type: "change item name",
name: "lion",
};
this.apply(changeNameEvent);
}
/**
*
* @param { ICommand } event
*/
eventHandler(event) {
switch (event.type) {
case "change item name":
const e = event;
this.#name = e.name;
}
}
}
const domain = new MyDomain([Item]);
domain.eventBus.register(
"change item name",
/**
*
* @param {MyDomain} domain
*/
(domain, event) => {
console.log("event.....", event);
}
);
domain.eventBus.registerSaga(($, d) => {
return $.pipe(
map((event) => {
return {
type: "done",
};
})
);
});
domain.commandBus
.register("change item name", (domain, { id, name }) => {
console.log("calll change comamnnn....");
const item = domain.itemRepository.get(id);
item?.changeName(name);
item?.commit();
})
.register("done", (d, c) => {
console.log("done !!!");
});
const item = domain.itemRepository.create();
domain.execute({
type: "change item name",
name: "hello",
id: item.id,
});