Skip to content

Commit

Permalink
feat: create notify method in event dispatcher
Browse files Browse the repository at this point in the history
  • Loading branch information
LeonardoCamargo31 committed Oct 30, 2023
1 parent 2073983 commit fb60b22
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/domain/event/@shared/event-dispatcher.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SendEmailWhenProductIsCreatedHandler } from '../product/handler/send-email-when-product-Is-created-handler'
import { ProductCreatedEvent } from '../product/product-created-event'
import { EventDispatcher } from './event-dispatcher'

describe('Domain events tests', () => {
Expand Down Expand Up @@ -31,4 +32,22 @@ describe('Domain events tests', () => {
eventDispatcher.unregisterAll()
expect(eventDispatcher.getEventHandlers.ProductCreatedEvent).toBeUndefined()
})

it('should notify all event handlers', () => {
const eventDispatcher = new EventDispatcher()
const eventHandler = new SendEmailWhenProductIsCreatedHandler()
const spyEventHandler = jest.spyOn(eventHandler, 'handler')
eventDispatcher.register('ProductCreatedEvent', eventHandler)
expect(eventDispatcher.getEventHandlers.ProductCreatedEvent[0]).toMatchObject(eventHandler)

const productCratedEvent = new ProductCreatedEvent({
name: 'product 1',
description: 'product 1 description',
price: 10.0
})

// quando o notify for chamado o SendEmailWhenProductIsCreatedHandler.handler() deve ser chamado
eventDispatcher.notify(productCratedEvent)
expect(spyEventHandler).toHaveBeenCalled()
})
})
9 changes: 8 additions & 1 deletion src/domain/event/@shared/event-dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,5 +29,12 @@ export class EventDispatcher implements EventDispatcherInterface {
this.eventHandlers = {}
}

notify: (event: EventInterface) => void
notify (event: EventInterface): void {
const eventName = event.constructor.name
if (this.eventHandlers[eventName]) {
this.eventHandlers[eventName].forEach((eventHandler) => {
eventHandler.handler(event)
})
}
}
}

0 comments on commit fb60b22

Please sign in to comment.