|
| 1 | +import { Inject, Injectable, OnApplicationBootstrap, OnModuleDestroy } from '@nestjs/common'; |
| 2 | +import { CommandBus } from '@nestjs/cqrs'; |
| 3 | + |
| 4 | +import { UserRegistrationWasStarted } from '@/events/user-registration-was-started.domain-event'; |
| 5 | +import { ApplicationEvent } from '@/module/application-command-events'; |
| 6 | +import { SendEmailMessageApplicationCommand, sendEmailMessageCommand } from '@/module/commands/send-email-message'; |
| 7 | +import { EmailConfirmationWasRequested } from '@/module/events/email-confirmation-was-requested.domain-event'; |
| 8 | +import { UserId } from '@/shared/domain.types'; |
| 9 | +import { ApplicationCommandFactory } from '@/write/shared/application/application-command.factory'; |
| 10 | +import { APPLICATION_SERVICE, ApplicationService } from '@/write/shared/application/application-service'; |
| 11 | +import { EVENT_REPOSITORY, EventRepository } from '@/write/shared/application/event-repository'; |
| 12 | +import { EventStreamName } from '@/write/shared/application/event-stream-name.value-object'; |
| 13 | +import { EventsSubscription } from '@/write/shared/application/events-subscription/events-subscription'; |
| 14 | +import { EventsSubscriptionsRegistry } from '@/write/shared/application/events-subscription/events-subscriptions-registry'; |
| 15 | + |
| 16 | +type AutomationEvent = EmailConfirmationWasRequested | UserRegistrationWasStarted; |
| 17 | + |
| 18 | +const SUBSCRIPTION_NAME = 'WhenEmailConfirmationWasRequestedThenSendEmailMessage'; |
| 19 | + |
| 20 | +@Injectable() |
| 21 | +export class EmailConfirmationWasRequestedEventHandler implements OnApplicationBootstrap, OnModuleDestroy { |
| 22 | + private eventsSubscription: EventsSubscription; |
| 23 | + |
| 24 | + constructor( |
| 25 | + private readonly commandBus: CommandBus, |
| 26 | + private readonly commandFactory: ApplicationCommandFactory, |
| 27 | + private readonly eventsSubscriptionsFactory: EventsSubscriptionsRegistry, |
| 28 | + @Inject(APPLICATION_SERVICE) |
| 29 | + private readonly applicationService: ApplicationService, |
| 30 | + @Inject(EVENT_REPOSITORY) |
| 31 | + private readonly eventRepository: EventRepository, |
| 32 | + ) {} |
| 33 | + |
| 34 | + async onApplicationBootstrap() { |
| 35 | + this.eventsSubscription = this.eventsSubscriptionsFactory |
| 36 | + .subscription(`${SUBSCRIPTION_NAME}_Automation_v1`) |
| 37 | + .onEvent<EmailConfirmationWasRequested>('EmailConfirmationWasRequested', (event) => |
| 38 | + this.onEmailConfirmationWasRequested(event), |
| 39 | + ) |
| 40 | + .onEvent<UserRegistrationWasStarted>('UserRegistrationWasStarted', (event) => |
| 41 | + this.onUserRegistrationWasStarted(event), |
| 42 | + ) |
| 43 | + .build(); |
| 44 | + await this.eventsSubscription.start(); |
| 45 | + } |
| 46 | + |
| 47 | + async onModuleDestroy() { |
| 48 | + await this.eventsSubscription.stop(); |
| 49 | + } |
| 50 | + |
| 51 | + async onUserRegistrationWasStarted(event: ApplicationEvent<UserRegistrationWasStarted>) { |
| 52 | + await this.publishAutomationEventAndSendEmailIfPossible(event); |
| 53 | + } |
| 54 | + |
| 55 | + async onEmailConfirmationWasRequested(event: ApplicationEvent<EmailConfirmationWasRequested>) { |
| 56 | + if (event.data.confirmationFor !== 'user-registration') return; |
| 57 | + |
| 58 | + await this.publishAutomationEventAndSendEmailIfPossible(event); |
| 59 | + } |
| 60 | + |
| 61 | + private static eventStreamFor(userId: string) { |
| 62 | + return EventStreamName.from(SUBSCRIPTION_NAME, userId); |
| 63 | + } |
| 64 | + |
| 65 | + private async publishAutomationEventAndSendEmailIfPossible(event: ApplicationEvent<AutomationEvent>) { |
| 66 | + const { userId } = event.data; |
| 67 | + const eventStream = EmailConfirmationWasRequestedEventHandler.eventStreamFor(userId); |
| 68 | + |
| 69 | + await this.applicationService.execute(eventStream, { ...event.metadata }, () => [event]); |
| 70 | + |
| 71 | + await this.sendEmailIfPossible(userId, event); |
| 72 | + } |
| 73 | + |
| 74 | + private async sendEmailIfPossible(userId: UserId, event: ApplicationEvent) { |
| 75 | + const eventStream = EmailConfirmationWasRequestedEventHandler.eventStreamFor(userId); |
| 76 | + |
| 77 | + const { pastEvents } = await this.eventRepository.readDomainStream<AutomationEvent>(eventStream); |
| 78 | + |
| 79 | + const { requestData, userEmail } = pastEvents.reduce<{ |
| 80 | + requestData?: EmailConfirmationWasRequested['data']; |
| 81 | + userEmail?: string; |
| 82 | + }>((state, e) => { |
| 83 | + switch (e.type) { |
| 84 | + case 'EmailConfirmationWasRequested': |
| 85 | + return { ...state, requestData: e.data }; |
| 86 | + case 'UserRegistrationWasStarted': |
| 87 | + return { ...state, userEmail: e.data.emailAddress }; |
| 88 | + default: |
| 89 | + return state; |
| 90 | + } |
| 91 | + }, {}); |
| 92 | + |
| 93 | + if (!userEmail || !requestData) { |
| 94 | + return; |
| 95 | + } |
| 96 | + |
| 97 | + const command = this.commandFactory.applicationCommand((idGenerator) => ({ |
| 98 | + class: SendEmailMessageApplicationCommand, |
| 99 | + ...sendEmailMessageCommand({ |
| 100 | + emailMessageId: idGenerator.generate(), |
| 101 | + to: userEmail, |
| 102 | + subject: 'Confirm your account', |
| 103 | + text: ` |
| 104 | + Click on link below to confirm your account registration: |
| 105 | + https://coderscamp.edu.pl/app/confirmation/${requestData.confirmationToken} |
| 106 | + `, |
| 107 | + html: ` |
| 108 | + <div> |
| 109 | + Click on link below to confirm your account registration: |
| 110 | + https://coderscamp.edu.pl/app/confirmation/${requestData.confirmationToken} |
| 111 | + </div> |
| 112 | + `, |
| 113 | + }), |
| 114 | + metadata: { correlationId: event.metadata.correlationId, causationId: event.id }, |
| 115 | + })); |
| 116 | + |
| 117 | + await this.commandBus.execute(command); |
| 118 | + } |
| 119 | +} |
0 commit comments