1.2.0 • Published 3 years ago
@unknovvn/eventmediatr v1.2.0
EventMediatr is minimal implementation of MediatR pattern based on eventEmitter
Install
$ npm install @unknovvn/eventmediatr
Usage
Publish
Should be used when request object has a constructor
const eventMediatr = new EventMediatr();
class ExampleRequest {
example;
constructor(example) {
this.example = example;
}
}
class ClassAsyncHandler {
handle = async (request) => {
console.log(
"ClassAsyncHandler handle starting with request = " +
JSON.stringify(request)
);
return await new Promise((resolve) => {
console.log("ClassAsyncHandler handle finished");
resolve(request.example);
});
};
}
eventMediatr.registerHandler("ExampleRequest", new ClassAsyncHandler());
eventMediatr
.publish(new ExampleRequest("Example value"))
.then((result) => console.log("ClassAsyncHandler result = " + result));
PublishByName
Should be used when request object doesn't have constructor
export default class AsyncHandler {
constructor() {}
handle = async () => {
console.log("Async handle starting");
return await new Promise((resolve) => {
setTimeout(() => {
console.log("Async handle finished");
resolve();
}, 2000);
});
};
}
export default class SyncHandler {
constructor() {}
handle = () => {
console.log("Async handle starting");
return setTimeout(() => {
console.log("Sync handle finished");
}, 2000);
};
}
const eventMediatr = new EventMediatr();
eventMediatr.registerHandler("async", new AsyncHandler());
eventMediatr.publishByName("async", {});
eventMediatr.registerSyncHandler("sync", new SyncHandler());
eventMediatr.publishByName("sync", {});
eventMediatr.publish("async", {});
eventMediatr.publish("sync", {});
License
MIT © Andžej Korovacki