Created
July 9, 2022 16:22
-
-
Save MaxLarue/27ab722e42706fde69cd595da6a326d2 to your computer and use it in GitHub Desktop.
event-service asynchronous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type EventType = string; | |
export interface Event { | |
type: EventType; | |
} | |
export interface EventPublisher { | |
publish<T extends Event>(event: Event): Promise<void> | |
} | |
export type EventHandler = (event: Event) => Promise<void> | |
export interface EventSubscribeService { | |
subscribe(eventType: EventType, handler: EventHandler) | |
} | |
@Injectable() | |
export class EventService implements EventPublisher, EventSubscribeService { | |
private multiMap<EventType, EventHandler> = new MultiMap() | |
async publish<T extends Event>(event: Event) { | |
for (const handler of this.multiMap) { | |
handler(event) | |
} | |
} | |
subscribe(eventType: EventType, handler: EventHandler) { | |
this.multiMap.add(eventType, handler) | |
} | |
} | |
@Injectable() | |
export class AsynchronousEventService implements EventPublisher, EventSubscribeService { | |
private multiMap<EventType, EventHandler> = new MultiMap() | |
constructor(@Inject(SqsService) private readonly sqsService: SqsService) {} | |
async publish<T extends Event>(event: Event) { | |
this.sqsService.publishEvent(event) | |
} | |
subscribe(eventType: EventType, handler: EventHandler) { | |
this.multiMap.add(eventType, handler) | |
} | |
main() { | |
const events = await this.sqsService.pollEvents() | |
for (const event of events) { | |
for (const handler of this.handlers) { | |
await handler(event) | |
} | |
} | |
setTimeout(() => this.main()) // or whatever makes it do this indefinitely | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment