Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support passing optional metadata to the domain emitter #148

Merged
merged 1 commit into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 24 additions & 3 deletions packages/core/lib/events/DomainEventEmitter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import { afterAll, beforeAll, expect } from 'vitest'
import type { Dependencies } from '../../test/testContext'
import { registerDependencies, TestEvents } from '../../test/testContext'

import type { CommonEventDefinitionSchemaType } from './eventTypes'
import type { CommonEventDefinitionConsumerSchemaType } from './eventTypes'
import { FakeListener } from './fakes/FakeListener'

const createdEventPayload: CommonEventDefinitionSchemaType<typeof TestEvents.created> = {
const createdEventPayload: CommonEventDefinitionConsumerSchemaType<typeof TestEvents.created> = {
payload: {
message: 'msg',
},
Expand All @@ -25,7 +25,7 @@ const createdEventPayload: CommonEventDefinitionSchemaType<typeof TestEvents.cre
},
}

const updatedEventPayload: CommonEventDefinitionSchemaType<typeof TestEvents.updated> = {
const updatedEventPayload: CommonEventDefinitionConsumerSchemaType<typeof TestEvents.updated> = {
...createdEventPayload,
type: 'entity.updated',
}
Expand Down Expand Up @@ -75,6 +75,27 @@ describe('AutopilotEventEmitter', () => {
expect(fakeListener.receivedEvents[0]).toMatchObject(expectedCreatedPayload)
})

it('emits event to anyListener with metadata', async () => {
const { eventEmitter } = diContainer.cradle
const fakeListener = new FakeListener(diContainer.cradle.eventRegistry.supportedEvents)
eventEmitter.onAny(fakeListener)

await eventEmitter.emit(TestEvents.created, createdEventPayload, {
correlationId: 'dummy',
})

await waitAndRetry(() => {
return fakeListener.receivedEvents.length > 0
})

expect(fakeListener.receivedEvents).toHaveLength(1)
expect(fakeListener.receivedEvents[0]).toMatchObject(expectedCreatedPayload)
expect(fakeListener.receivedMetadata).toHaveLength(1)
expect(fakeListener.receivedMetadata[0]).toMatchObject({
correlationId: 'dummy',
})
})

it('emits event to singleListener', async () => {
const { eventEmitter } = diContainer.cradle
const fakeListener = new FakeListener(diContainer.cradle.eventRegistry.supportedEvents)
Expand Down
16 changes: 10 additions & 6 deletions packages/core/lib/events/DomainEventEmitter.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
import { InternalError } from '@lokalise/node-core'

import type { MessageMetadataType } from '../messages/baseMessageSchemas'

import type { EventRegistry } from './EventRegistry'
import type {
EventHandler,
AnyEventHandler,
SingleEventHandler,
CommonEventDefinition,
CommonEventDefinitionSchemaType,
CommonEventDefinitionConsumerSchemaType,
EventTypeNames,
CommonEventDefinitionPublisherSchemaType,
} from './eventTypes'

export class DomainEventEmitter<SupportedEvents extends CommonEventDefinition[]> {
private readonly eventRegistry: EventRegistry<SupportedEvents>

private readonly eventHandlerMap: Record<
string,
EventHandler<CommonEventDefinitionSchemaType<SupportedEvents[number]>>[]
EventHandler<CommonEventDefinitionConsumerSchemaType<SupportedEvents[number]>>[]
> = {}
private readonly anyHandlers: AnyEventHandler<SupportedEvents>[] = []

Expand All @@ -25,9 +28,10 @@ export class DomainEventEmitter<SupportedEvents extends CommonEventDefinition[]>

public async emit<SupportedEvent extends SupportedEvents[number]>(
supportedEvent: SupportedEvent,
data: Omit<CommonEventDefinitionSchemaType<SupportedEvent>, 'type'>,
data: Omit<CommonEventDefinitionPublisherSchemaType<SupportedEvent>, 'type'>,
metadata?: Partial<MessageMetadataType>,
) {
const eventTypeName = supportedEvent.consumerSchema.shape.type.value
const eventTypeName = supportedEvent.publisherSchema.shape.type.value

if (!this.eventRegistry.isSupportedEvent(eventTypeName)) {
throw new InternalError({
Expand All @@ -52,12 +56,12 @@ export class DomainEventEmitter<SupportedEvents extends CommonEventDefinition[]>

if (eventHandlers) {
for (const handler of eventHandlers) {
await handler.handleEvent(validatedEvent)
await handler.handleEvent(validatedEvent, metadata)
}
}

for (const handler of this.anyHandlers) {
await handler.handleEvent(validatedEvent)
await handler.handleEvent(validatedEvent, metadata)
}
}

Expand Down
25 changes: 19 additions & 6 deletions packages/core/lib/events/eventTypes.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import type { ZodObject, ZodTypeAny } from 'zod'
import type z from 'zod'

import type { MessageMetadataType } from '../messages/baseMessageSchemas'

import type { CONSUMER_BASE_EVENT_SCHEMA, PUBLISHER_BASE_EVENT_SCHEMA } from './baseEventSchemas'

export type EventTypeNames<EventDefinition extends CommonEventDefinition> =
CommonEventDefinitionSchemaType<EventDefinition>['type']
CommonEventDefinitionConsumerSchemaType<EventDefinition>['type']

export type CommonEventDefinition = {
consumerSchema: ZodObject<
Expand All @@ -16,19 +18,27 @@ export type CommonEventDefinition = {
schemaVersion?: string
}

export type CommonEventDefinitionSchemaType<T extends CommonEventDefinition> = z.infer<
export type CommonEventDefinitionConsumerSchemaType<T extends CommonEventDefinition> = z.infer<
T['consumerSchema']
>

export type CommonEventDefinitionPublisherSchemaType<T extends CommonEventDefinition> = z.infer<
T['publisherSchema']
>

export type EventHandler<
EventDefinitionSchema extends
CommonEventDefinitionSchemaType<CommonEventDefinition> = CommonEventDefinitionSchemaType<CommonEventDefinition>,
CommonEventDefinitionConsumerSchemaType<CommonEventDefinition> = CommonEventDefinitionConsumerSchemaType<CommonEventDefinition>,
MetadataDefinitionSchema extends Partial<MessageMetadataType> = Partial<MessageMetadataType>,
> = {
handleEvent(event: EventDefinitionSchema): void | Promise<void>
handleEvent(
event: EventDefinitionSchema,
metadata?: MetadataDefinitionSchema,
): void | Promise<void>
}

export type AnyEventHandler<EventDefinitions extends CommonEventDefinition[]> = EventHandler<
CommonEventDefinitionSchemaType<EventDefinitions[number]>
CommonEventDefinitionConsumerSchemaType<EventDefinitions[number]>
>

export type SingleEventHandler<
Expand All @@ -39,4 +49,7 @@ export type SingleEventHandler<
type EventFromArrayByTypeName<
EventDefinition extends CommonEventDefinition[],
EventTypeName extends EventTypeNames<EventDefinition[number]>,
> = Extract<CommonEventDefinitionSchemaType<EventDefinition[number]>, { type: EventTypeName }>
> = Extract<
CommonEventDefinitionConsumerSchemaType<EventDefinition[number]>,
{ type: EventTypeName }
>
8 changes: 7 additions & 1 deletion packages/core/lib/events/fakes/FakeListener.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import type { MessageMetadataType } from '../../messages/baseMessageSchemas'
import type { AnyEventHandler, CommonEventDefinition } from '../eventTypes'

export class FakeListener<SupportedEvents extends CommonEventDefinition[]>
implements AnyEventHandler<SupportedEvents>
{
public receivedEvents: SupportedEvents[number]['consumerSchema']['_output'][] = []
public receivedMetadata: MessageMetadataType[] = []

constructor(_supportedEvents: SupportedEvents) {
this.receivedEvents = []
}

handleEvent(event: SupportedEvents[number]['consumerSchema']['_output']): void | Promise<void> {
handleEvent(
event: SupportedEvents[number]['consumerSchema']['_output'],
metadata: MessageMetadataType,
): void | Promise<void> {
this.receivedEvents.push(event)
this.receivedMetadata.push(metadata)
}
}
Loading