@robinmalfait/event-source 0.0.14 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +13 -2
- package/dist/index.d.ts +13 -2
- package/dist/index.js +8 -8
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var I=Object.create;var h=Object.defineProperty;var _=Object.getOwnPropertyDescriptor;var J=Object.getOwnPropertyNames;var Q=Object.getPrototypeOf,R=Object.prototype.hasOwnProperty;var F=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},C=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of J(e))!R.call(r,a)&&a!==t&&h(r,a,{get:()=>e[a],enumerable:!(n=_(e,a))||n.enumerable});return r};var V=(r,e,t)=>(t=r!=null?I(Q(r)):{},C(e||!r||!r.__esModule?h(t,"default",{value:r,enumerable:!0}):t,r)),Y=r=>C(h({},"__esModule",{value:!0}),r);var G={};F(G,{Aggregate:()=>A,Command:()=>W,Event:()=>Z,EventSource:()=>y,Projector:()=>m,abort:()=>c,createEventMapper:()=>k,createTestEventStore:()=>B,objectToYaml:()=>f});module.exports=Y(G);function j(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,j),t}function c(r,e){let t=j(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,c),t}function S(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&S(r[e]);return r}var U={NODE_ENV:process.env.NODE_ENV},A=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){U.NODE_ENV==="test"&&S(e);let t=this.apply[e.eventName];t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?c(`Aggregate "${this.constructor.name}" has no method:
|
|
2
2
|
|
|
3
3
|
apply = {
|
|
4
4
|
${e.eventName}(event) {
|
|
@@ -14,23 +14,23 @@ apply = {
|
|
|
14
14
|
// ...
|
|
15
15
|
}`));try{t(e)}catch(n){n instanceof Error&&console.error(`An error occurred inside your "%s" function:
|
|
16
16
|
`,e.eventName,n.stack?.split(`
|
|
17
|
-
`).map(
|
|
18
|
-
`))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function W(r,e=null){return{type:r,payload:e}}var
|
|
17
|
+
`).map(a=>` ${a}`).join(`
|
|
18
|
+
`))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function W(r,e=null){return{type:r,payload:e}}var z=require("crypto");function Z(r,e,t=null,n=null){return{aggregateId:e,eventId:(0,z.randomUUID)(),eventName:r,payload:t,metadata:n,recordedAt:new Date,version:-1}}var L=V(require("yamlify-object"),1),q={indent:" ",colors:{date:v,error:v,symbol:v,string:v,number:v,boolean:v,null:v,undefined:v}};function v(r){return r}function f(r){return r instanceof Error?f({...r}):(0,L.default)(r,q).split(`
|
|
19
19
|
`).slice(1).join(`
|
|
20
|
-
`)}var T=new WeakMap;function g(r,e){if(T.has(r)){let t=T.get(r);for(let n in e)t[n]=e[n]}else T.set(r,e)}function
|
|
20
|
+
`)}var T=new WeakMap;function g(r,e){if(T.has(r)){let t=T.get(r);for(let n in e)t[n]=e[n]}else T.set(r,e)}function b(r){return T.get(r)}var x=class{constructor(){g(this,{jobs:[],state:0})}get length(){return b(this).jobs.length}async start(){let{state:e,jobs:t}=b(this);if(!(e===1||t.length<=0)){for(g(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}g(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:a}=b(this);a.push({handle:e,resolve:t,reject:n}),setImmediate(()=>this.start())})}};var m=class{apply;initializer(){}#e=new x;async init(e){this.initializer&&await this.#e.push(()=>this.initializer?.());let t=await e.loadEvents();await Promise.all(t.map(n=>this.applyEvent(n)))}async applyEvent(e){await this.#e.push(()=>this.apply?.[e.eventName]?.(e)),await this.#e.push(()=>this.project(e))}project(e){}},y=class r{constructor(e,t,n,a,o){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=a;this.eventMetadataEnhancers=o}static builder(e){return new M(e)}static new(e,t,n,a,o){return new r(e,t,n,a,o)}async resetProjections(){await Promise.all(this.projectors.map(e=>e.init(this)))}async dispatch(e){return this.commandHandlers.has(e.type)||c(`There is no command handler for the "${e.type}" command`),await this.commandHandlers.get(e.type)(e,this),e}async loadEvents(){return this.store.loadEvents()}async load(e,t){let n=await this.store.load(t);return n.length<=0&&c(`Aggregate(${e.constructor.name}) with ID(${t}) does not exist.`,{aggregate:e.constructor.name,aggregateId:t}),e.replayEvents(n)}async persist(e){let t=e.releaseEvents();if(this.eventMetadataEnhancers.length>0)for(let n of t){let a=n.metadata;n.metadata={};for(let o of this.eventMetadataEnhancers)Object.assign(n.metadata,await o(n));typeof a=="object"&&a!==null&&Object.assign(n.metadata,a)}await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async a=>{try{await a.applyEvent(n)}catch(o){throw o instanceof Error&&console.error(`An error occurred in one of your projections: ${a.name}, given an event`,o.stack?.split(`
|
|
21
21
|
`).map(E=>` ${E}`).join(`
|
|
22
|
-
`)),
|
|
22
|
+
`)),o}})),await Promise.all(this.eventHandlers.map(async a=>{try{await a(n,this)}catch(o){throw o instanceof Error&&console.error(`An error occurred in one of your event handlers: ${a.name}, given an event`,o.stack?.split(`
|
|
23
23
|
`).map(E=>` ${E}`).join(`
|
|
24
|
-
`)),
|
|
24
|
+
`)),o}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},M=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];eventMetadataEnhancers=[];build(){return y.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers,this.eventMetadataEnhancers)}addCommandHandler(e,t){return this.commandHandlers.has(e)&&c(`A command handler for the "${e}" command already exists`),this.commandHandlers.set(e,t),this}addProjector(e){return this.projectors.push(e),this}addEventHandler(e){return this.eventHandlers.push(e),this}metadata(e){return this.eventMetadataEnhancers.push(e),this}};function k(r){return(e,t)=>r[e.eventName]?.(e,t)}var N=Symbol("__placeholder__");function D(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var $=class extends m{constructor(t=[],n=[]){super();this.db=t;this.producedEvents=n}apply={};name="test-recording-projector";initializer(){this.db.splice(0)}project(t){this.producedEvents.push(t)}};function B(r,e=[]){let t=new $,n=y.builder({load(s){return t.db.filter(i=>i.aggregateId===s)},loadEvents(){return t.db},persist(s){t.db.push(...s)}});for(let s of e)n.addProjector(s);n.addProjector(t);for(let[s,i]of Object.entries(r))n.addCommandHandler(s,i);let a=n.build(),o,E=!1,w={___:N,async given(s=[]){t.db.push(...s)},async when(s){try{return await a.dispatch(typeof s=="function"?s():s)}catch(i){return i instanceof Error&&(o=i),i}},async then(s){if(E=!0,s instanceof Error){let u=s;D(()=>{if(o?.message!==u?.message)throw new Error(`Expected error message to be:
|
|
25
25
|
|
|
26
26
|
${u.message}
|
|
27
27
|
|
|
28
28
|
But got:
|
|
29
29
|
|
|
30
|
-
${
|
|
31
|
-
${f(
|
|
30
|
+
${o?.message}`)},w.then);return}let i=s;if(o)throw Object.keys(o).length>0&&(o.message=["With properties:",`
|
|
31
|
+
${f(o)}
|
|
32
32
|
|
|
33
33
|
---
|
|
34
34
|
|
|
35
35
|
`].join(`
|
|
36
|
-
`)),
|
|
36
|
+
`)),o;D(()=>{if(i.length!==t.producedEvents.length)throw new Error(`Expected ${i.length} events, but got ${t.producedEvents.length} events.`);for(let[u,p]of i.entries()){let{aggregateId:H,eventName:O,payload:d}=t.producedEvents[u];if(p.aggregateId===N)throw new Error("Expected an `aggregateId`, but got `___` instead.");if(p.aggregateId!==H)throw new Error(`Expected aggregateId to be ${p.aggregateId}, but got ${H}.`);if(p.eventName!==O)throw new Error(`Expected eventName to be ${p.eventName}, but got ${O}.`);if((p.payload===null||p.payload===void 0)&&JSON.stringify(p.payload)!==JSON.stringify(d))throw new Error(`Expected payload to be ${JSON.stringify(p.payload)}, but got ${JSON.stringify(d)}.`);for(let l in p.payload){let P=p.payload[l];if(P===N){if(!(l in d))throw new Error(`Expected payload to have property ${l}, but it does not.`);if(d[l]===null||d[l]===void 0)throw new Error(`Expected payload to have property ${l}, but it is ${d[l]}.`)}else if(d[l]!==P)throw new Error(`Expected payload.${l} to be ${P}, but got ${d[l]}.`)}}},w.then)}};return w}0&&(module.exports={Aggregate,Command,Event,EventSource,Projector,abort,createEventMapper,createTestEventStore,objectToYaml});
|
package/dist/index.d.cts
CHANGED
|
@@ -44,6 +44,11 @@ declare function abort<T>(message: string, attributes?: T): void;
|
|
|
44
44
|
|
|
45
45
|
declare function objectToYaml<T extends Object>(object: T): string;
|
|
46
46
|
|
|
47
|
+
interface JSON {
|
|
48
|
+
[x: string]: string | number | boolean | Date | JSON | JSONArray;
|
|
49
|
+
}
|
|
50
|
+
interface JSONArray extends Array<string | number | boolean | Date | JSON | JSONArray> {
|
|
51
|
+
}
|
|
47
52
|
type MaybePromise<T> = T | Promise<T>;
|
|
48
53
|
interface EventStore {
|
|
49
54
|
persist(events: EventType[]): MaybePromise<void>;
|
|
@@ -53,6 +58,9 @@ interface EventStore {
|
|
|
53
58
|
interface EventHandler {
|
|
54
59
|
(event: EventType, es: EventSource): MaybePromise<unknown>;
|
|
55
60
|
}
|
|
61
|
+
interface MetadataEnhancer {
|
|
62
|
+
(event: EventType): MaybePromise<JSON>;
|
|
63
|
+
}
|
|
56
64
|
type ApplyConcreteProjectorEvents<Events extends EventType> = Events extends EventType<infer EventName, any> ? {
|
|
57
65
|
[T in EventName]: (event: Extract<Events, {
|
|
58
66
|
eventName: T;
|
|
@@ -91,9 +99,10 @@ declare class EventSource {
|
|
|
91
99
|
private commandHandlers;
|
|
92
100
|
private projectors;
|
|
93
101
|
private eventHandlers;
|
|
102
|
+
private eventMetadataEnhancers;
|
|
94
103
|
private constructor();
|
|
95
104
|
static builder(store: EventStore): EventSourceBuilder;
|
|
96
|
-
static new(store: EventStore, commandHandlers: Map<string, CommandHandler>, projectors: Projector[], eventHandlers: EventHandler[]): EventSource;
|
|
105
|
+
static new(store: EventStore, commandHandlers: Map<string, CommandHandler>, projectors: Projector[], eventHandlers: EventHandler[], eventMetadataEnhancers: MetadataEnhancer[]): EventSource;
|
|
97
106
|
resetProjections(): Promise<void>;
|
|
98
107
|
dispatch<T extends CommandType>(command: T): Promise<T>;
|
|
99
108
|
loadEvents(): Promise<EventType<any, any, any>[]>;
|
|
@@ -106,11 +115,13 @@ declare class EventSourceBuilder {
|
|
|
106
115
|
private commandHandlers;
|
|
107
116
|
private projectors;
|
|
108
117
|
private eventHandlers;
|
|
118
|
+
private eventMetadataEnhancers;
|
|
109
119
|
constructor(store: EventStore);
|
|
110
120
|
build(): EventSource;
|
|
111
121
|
addCommandHandler(commandType: string, handler: CommandHandler): this;
|
|
112
122
|
addProjector(projector: Projector): this;
|
|
113
123
|
addEventHandler(eventHandler: EventHandler): this;
|
|
124
|
+
metadata(metadataEnhancer: MetadataEnhancer): this;
|
|
114
125
|
}
|
|
115
126
|
|
|
116
127
|
type EventMapper = Record<string, (event: EventType, es: EventSource) => void>;
|
|
@@ -123,4 +134,4 @@ declare function createTestEventStore(commandHandlers: Record<string, CommandHan
|
|
|
123
134
|
then(expectation: EventType[] | Error): Promise<void>;
|
|
124
135
|
};
|
|
125
136
|
|
|
126
|
-
export { Aggregate, type ApplyEvents, Command, type CommandHandler, type CommandType, Event, type EventHandler, EventSource, type EventStore, type EventType, type PayloadOf, Projector, type TypeOf, abort, createEventMapper, createTestEventStore, objectToYaml };
|
|
137
|
+
export { Aggregate, type ApplyEvents, Command, type CommandHandler, type CommandType, Event, type EventHandler, EventSource, type EventStore, type EventType, type MetadataEnhancer, type PayloadOf, Projector, type TypeOf, abort, createEventMapper, createTestEventStore, objectToYaml };
|
package/dist/index.d.ts
CHANGED
|
@@ -44,6 +44,11 @@ declare function abort<T>(message: string, attributes?: T): void;
|
|
|
44
44
|
|
|
45
45
|
declare function objectToYaml<T extends Object>(object: T): string;
|
|
46
46
|
|
|
47
|
+
interface JSON {
|
|
48
|
+
[x: string]: string | number | boolean | Date | JSON | JSONArray;
|
|
49
|
+
}
|
|
50
|
+
interface JSONArray extends Array<string | number | boolean | Date | JSON | JSONArray> {
|
|
51
|
+
}
|
|
47
52
|
type MaybePromise<T> = T | Promise<T>;
|
|
48
53
|
interface EventStore {
|
|
49
54
|
persist(events: EventType[]): MaybePromise<void>;
|
|
@@ -53,6 +58,9 @@ interface EventStore {
|
|
|
53
58
|
interface EventHandler {
|
|
54
59
|
(event: EventType, es: EventSource): MaybePromise<unknown>;
|
|
55
60
|
}
|
|
61
|
+
interface MetadataEnhancer {
|
|
62
|
+
(event: EventType): MaybePromise<JSON>;
|
|
63
|
+
}
|
|
56
64
|
type ApplyConcreteProjectorEvents<Events extends EventType> = Events extends EventType<infer EventName, any> ? {
|
|
57
65
|
[T in EventName]: (event: Extract<Events, {
|
|
58
66
|
eventName: T;
|
|
@@ -91,9 +99,10 @@ declare class EventSource {
|
|
|
91
99
|
private commandHandlers;
|
|
92
100
|
private projectors;
|
|
93
101
|
private eventHandlers;
|
|
102
|
+
private eventMetadataEnhancers;
|
|
94
103
|
private constructor();
|
|
95
104
|
static builder(store: EventStore): EventSourceBuilder;
|
|
96
|
-
static new(store: EventStore, commandHandlers: Map<string, CommandHandler>, projectors: Projector[], eventHandlers: EventHandler[]): EventSource;
|
|
105
|
+
static new(store: EventStore, commandHandlers: Map<string, CommandHandler>, projectors: Projector[], eventHandlers: EventHandler[], eventMetadataEnhancers: MetadataEnhancer[]): EventSource;
|
|
97
106
|
resetProjections(): Promise<void>;
|
|
98
107
|
dispatch<T extends CommandType>(command: T): Promise<T>;
|
|
99
108
|
loadEvents(): Promise<EventType<any, any, any>[]>;
|
|
@@ -106,11 +115,13 @@ declare class EventSourceBuilder {
|
|
|
106
115
|
private commandHandlers;
|
|
107
116
|
private projectors;
|
|
108
117
|
private eventHandlers;
|
|
118
|
+
private eventMetadataEnhancers;
|
|
109
119
|
constructor(store: EventStore);
|
|
110
120
|
build(): EventSource;
|
|
111
121
|
addCommandHandler(commandType: string, handler: CommandHandler): this;
|
|
112
122
|
addProjector(projector: Projector): this;
|
|
113
123
|
addEventHandler(eventHandler: EventHandler): this;
|
|
124
|
+
metadata(metadataEnhancer: MetadataEnhancer): this;
|
|
114
125
|
}
|
|
115
126
|
|
|
116
127
|
type EventMapper = Record<string, (event: EventType, es: EventSource) => void>;
|
|
@@ -123,4 +134,4 @@ declare function createTestEventStore(commandHandlers: Record<string, CommandHan
|
|
|
123
134
|
then(expectation: EventType[] | Error): Promise<void>;
|
|
124
135
|
};
|
|
125
136
|
|
|
126
|
-
export { Aggregate, type ApplyEvents, Command, type CommandHandler, type CommandType, Event, type EventHandler, EventSource, type EventStore, type EventType, type PayloadOf, Projector, type TypeOf, abort, createEventMapper, createTestEventStore, objectToYaml };
|
|
137
|
+
export { Aggregate, type ApplyEvents, Command, type CommandHandler, type CommandType, Event, type EventHandler, EventSource, type EventStore, type EventType, type MetadataEnhancer, type PayloadOf, Projector, type TypeOf, abort, createEventMapper, createTestEventStore, objectToYaml };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function w(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,w),t}function d(r,e){let t=w(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,d),t}function P(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&P(r[e]);return r}var
|
|
1
|
+
function w(r,e){let t=Object.assign(new Error(r),e);return t.stack,Error.captureStackTrace&&Error.captureStackTrace(t,w),t}function d(r,e){let t=w(r,e);throw Error.captureStackTrace&&Error.captureStackTrace(t,d),t}function P(r){Object.freeze(r);for(let e of Object.getOwnPropertyNames(r))r.hasOwnProperty(e)&&r[e]!==null&&(typeof r[e]=="object"||typeof r[e]=="function")&&!Object.isFrozen(r[e])&&P(r[e]);return r}var C={NODE_ENV:process.env.NODE_ENV},H=class{#e=0;#t=[];replayEvents(e=[]){for(let t of e)this.applyAnEvent(t);return this}applyAnEvent(e){C.NODE_ENV==="test"&&P(e);let t=this.apply[e.eventName];t==null&&(e.eventName.match(/^[$A-Z_][0-9A-Z_$]*$/i)?d(`Aggregate "${this.constructor.name}" has no method:
|
|
2
2
|
|
|
3
3
|
apply = {
|
|
4
4
|
${e.eventName}(event) {
|
|
@@ -14,23 +14,23 @@ apply = {
|
|
|
14
14
|
// ...
|
|
15
15
|
}`));try{t(e)}catch(n){n instanceof Error&&console.error(`An error occurred inside your "%s" function:
|
|
16
16
|
`,e.eventName,n.stack?.split(`
|
|
17
|
-
`).map(
|
|
18
|
-
`))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function Y(r,e=null){return{type:r,payload:e}}import{randomUUID as
|
|
17
|
+
`).map(o=>` ${o}`).join(`
|
|
18
|
+
`))}finally{this.#e++}return this}recordThat(e){let t={...e,version:this.#e};return this.applyAnEvent(t),this.#t.push(t),this}releaseEvents(){return this.#t.splice(0)}};function Y(r,e=null){return{type:r,payload:e}}import{randomUUID as z}from"node:crypto";function Z(r,e,t=null,n=null){return{aggregateId:e,eventId:z(),eventName:r,payload:t,metadata:n,recordedAt:new Date,version:-1}}import L from"yamlify-object";var k={indent:" ",colors:{date:v,error:v,symbol:v,string:v,number:v,boolean:v,null:v,undefined:v}};function v(r){return r}function j(r){return r instanceof Error?j({...r}):L(r,k).split(`
|
|
19
19
|
`).slice(1).join(`
|
|
20
|
-
`)}var u=new WeakMap;function h(r,e){if(u.has(r)){let t=u.get(r);for(let n in e)t[n]=e[n]}else u.set(r,e)}function f(r){return u.get(r)}var T=class{constructor(){h(this,{jobs:[],state:0})}get length(){return f(this).jobs.length}async start(){let{state:e,jobs:t}=f(this);if(!(e===1||t.length<=0)){for(h(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}h(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:
|
|
20
|
+
`)}var u=new WeakMap;function h(r,e){if(u.has(r)){let t=u.get(r);for(let n in e)t[n]=e[n]}else u.set(r,e)}function f(r){return u.get(r)}var T=class{constructor(){h(this,{jobs:[],state:0})}get length(){return f(this).jobs.length}async start(){let{state:e,jobs:t}=f(this);if(!(e===1||t.length<=0)){for(h(this,{state:1});t.length>0;){let n=t.shift();await Promise.resolve().then(n.handle).then(n.resolve,n.reject)}h(this,{state:0})}}push(e){return new Promise((t,n)=>{let{jobs:o}=f(this);o.push({handle:e,resolve:t,reject:n}),setImmediate(()=>this.start())})}};var g=class{apply;initializer(){}#e=new T;async init(e){this.initializer&&await this.#e.push(()=>this.initializer?.());let t=await e.loadEvents();await Promise.all(t.map(n=>this.applyEvent(n)))}async applyEvent(e){await this.#e.push(()=>this.apply?.[e.eventName]?.(e)),await this.#e.push(()=>this.project(e))}project(e){}},E=class r{constructor(e,t,n,o,a){this.store=e;this.commandHandlers=t;this.projectors=n;this.eventHandlers=o;this.eventMetadataEnhancers=a}static builder(e){return new S(e)}static new(e,t,n,o,a){return new r(e,t,n,o,a)}async resetProjections(){await Promise.all(this.projectors.map(e=>e.init(this)))}async dispatch(e){return this.commandHandlers.has(e.type)||d(`There is no command handler for the "${e.type}" command`),await this.commandHandlers.get(e.type)(e,this),e}async loadEvents(){return this.store.loadEvents()}async load(e,t){let n=await this.store.load(t);return n.length<=0&&d(`Aggregate(${e.constructor.name}) with ID(${t}) does not exist.`,{aggregate:e.constructor.name,aggregateId:t}),e.replayEvents(n)}async persist(e){let t=e.releaseEvents();if(this.eventMetadataEnhancers.length>0)for(let n of t){let o=n.metadata;n.metadata={};for(let a of this.eventMetadataEnhancers)Object.assign(n.metadata,await a(n));typeof o=="object"&&o!==null&&Object.assign(n.metadata,o)}await this.store.persist(t);for(let n of t)await Promise.all(this.projectors.map(async o=>{try{await o.applyEvent(n)}catch(a){throw a instanceof Error&&console.error(`An error occurred in one of your projections: ${o.name}, given an event`,a.stack?.split(`
|
|
21
21
|
`).map(y=>` ${y}`).join(`
|
|
22
|
-
`)),a}})),await Promise.all(this.eventHandlers.map(async
|
|
22
|
+
`)),a}})),await Promise.all(this.eventHandlers.map(async o=>{try{await o(n,this)}catch(a){throw a instanceof Error&&console.error(`An error occurred in one of your event handlers: ${o.name}, given an event`,a.stack?.split(`
|
|
23
23
|
`).map(y=>` ${y}`).join(`
|
|
24
|
-
`)),a}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},
|
|
24
|
+
`)),a}}))}async loadPersist(e,t,n){return await this.load(e,t),await n(e),this.persist(e)}},S=class{constructor(e){this.store=e}commandHandlers=new Map;projectors=[];eventHandlers=[];eventMetadataEnhancers=[];build(){return E.new(this.store,this.commandHandlers,this.projectors,this.eventHandlers,this.eventMetadataEnhancers)}addCommandHandler(e,t){return this.commandHandlers.has(e)&&d(`A command handler for the "${e}" command already exists`),this.commandHandlers.set(e,t),this}addProjector(e){return this.projectors.push(e),this}addEventHandler(e){return this.eventHandlers.push(e),this}metadata(e){return this.eventMetadataEnhancers.push(e),this}};function D(r){return(e,t)=>r[e.eventName]?.(e,t)}var A=Symbol("__placeholder__");function O(r,e){try{return r()}catch(t){throw Error.captureStackTrace&&t instanceof Error&&Error.captureStackTrace(t,e),t}}var M=class extends g{constructor(t=[],n=[]){super();this.db=t;this.producedEvents=n}apply={};name="test-recording-projector";initializer(){this.db.splice(0)}project(t){this.producedEvents.push(t)}};function pe(r,e=[]){let t=new M,n=E.builder({load(s){return t.db.filter(i=>i.aggregateId===s)},loadEvents(){return t.db},persist(s){t.db.push(...s)}});for(let s of e)n.addProjector(s);n.addProjector(t);for(let[s,i]of Object.entries(r))n.addCommandHandler(s,i);let o=n.build(),a,y=!1,b={___:A,async given(s=[]){t.db.push(...s)},async when(s){try{return await o.dispatch(typeof s=="function"?s():s)}catch(i){return i instanceof Error&&(a=i),i}},async then(s){if(y=!0,s instanceof Error){let m=s;O(()=>{if(a?.message!==m?.message)throw new Error(`Expected error message to be:
|
|
25
25
|
|
|
26
26
|
${m.message}
|
|
27
27
|
|
|
28
28
|
But got:
|
|
29
29
|
|
|
30
|
-
${a?.message}`)},
|
|
30
|
+
${a?.message}`)},b.then);return}let i=s;if(a)throw Object.keys(a).length>0&&(a.message=["With properties:",`
|
|
31
31
|
${j(a)}
|
|
32
32
|
|
|
33
33
|
---
|
|
34
34
|
|
|
35
35
|
`].join(`
|
|
36
|
-
`)),a;
|
|
36
|
+
`)),a;O(()=>{if(i.length!==t.producedEvents.length)throw new Error(`Expected ${i.length} events, but got ${t.producedEvents.length} events.`);for(let[m,p]of i.entries()){let{aggregateId:N,eventName:$,payload:c}=t.producedEvents[m];if(p.aggregateId===A)throw new Error("Expected an `aggregateId`, but got `___` instead.");if(p.aggregateId!==N)throw new Error(`Expected aggregateId to be ${p.aggregateId}, but got ${N}.`);if(p.eventName!==$)throw new Error(`Expected eventName to be ${p.eventName}, but got ${$}.`);if((p.payload===null||p.payload===void 0)&&JSON.stringify(p.payload)!==JSON.stringify(c))throw new Error(`Expected payload to be ${JSON.stringify(p.payload)}, but got ${JSON.stringify(c)}.`);for(let l in p.payload){let x=p.payload[l];if(x===A){if(!(l in c))throw new Error(`Expected payload to have property ${l}, but it does not.`);if(c[l]===null||c[l]===void 0)throw new Error(`Expected payload to have property ${l}, but it is ${c[l]}.`)}else if(c[l]!==x)throw new Error(`Expected payload.${l} to be ${x}, but got ${c[l]}.`)}}},b.then)}};return b}export{H as Aggregate,Y as Command,Z as Event,E as EventSource,g as Projector,d as abort,D as createEventMapper,pe as createTestEventStore,j as objectToYaml};
|
package/package.json
CHANGED