event-handler.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. import { LanguageCode } from '@vendure/common/lib/generated-types';
  2. import { Type } from '@vendure/common/lib/shared-types';
  3. import { Injector, Logger } from '@vendure/core';
  4. import { loggerCtx } from './constants';
  5. import { EmailEventListener, EmailTemplateConfig, SetTemplateVarsFn } from './event-listener';
  6. import { EventWithAsyncData, EventWithContext, IntermediateEmailDetails, LoadDataFn } from './types';
  7. /**
  8. * @description
  9. * The EmailEventHandler defines how the EmailPlugin will respond to a given event.
  10. *
  11. * A handler is created by creating a new {@link EmailEventListener} and calling the `.on()` method
  12. * to specify which event to respond to.
  13. *
  14. * @example
  15. * ```ts
  16. * const confirmationHandler = new EmailEventListener('order-confirmation')
  17. * .on(OrderStateTransitionEvent)
  18. * .filter(event => event.toState === 'PaymentSettled')
  19. * .setRecipient(event => event.order.customer.emailAddress)
  20. * .setSubject(`Order confirmation for #{{ order.code }}`)
  21. * .setTemplateVars(event => ({ order: event.order }));
  22. * ```
  23. *
  24. * This example creates a handler which listens for the `OrderStateTransitionEvent` and if the Order has
  25. * transitioned to the `'PaymentSettled'` state, it will generate and send an email.
  26. *
  27. * ## Handling other languages
  28. *
  29. * By default, the handler will respond to all events on all channels and use the same subject ("Order confirmation for #12345" above)
  30. * and body template. Where the server is intended to support multiple languages, the `.addTemplate()` method may be used
  31. * to defined the subject and body template for specific language and channel combinations.
  32. *
  33. * @example
  34. * ```ts
  35. * const extendedConfirmationHandler = confirmationHandler
  36. * .addTemplate({
  37. * channelCode: 'default',
  38. * languageCode: LanguageCode.de,
  39. * templateFile: 'body.de.hbs',
  40. * subject: 'Bestellbestätigung für #{{ order.code }}',
  41. * })
  42. * ```
  43. *
  44. * @docsCategory EmailPlugin
  45. */
  46. export class EmailEventHandler<T extends string = string, Event extends EventWithContext = EventWithContext> {
  47. private setRecipientFn: (event: Event) => string;
  48. private setTemplateVarsFn: SetTemplateVarsFn<Event>;
  49. private filterFns: Array<(event: Event) => boolean> = [];
  50. private configurations: EmailTemplateConfig[] = [];
  51. private defaultSubject: string;
  52. private from: string;
  53. private _mockEvent: Omit<Event, 'ctx' | 'data'> | undefined;
  54. constructor(public listener: EmailEventListener<T>, public event: Type<Event>) {}
  55. /** @internal */
  56. get type(): T {
  57. return this.listener.type;
  58. }
  59. /** @internal */
  60. get mockEvent(): Omit<Event, 'ctx' | 'data'> | undefined {
  61. return this._mockEvent;
  62. }
  63. /**
  64. * @description
  65. * Defines a predicate function which is used to determine whether the event will trigger an email.
  66. * Multiple filter functions may be defined.
  67. */
  68. filter(filterFn: (event: Event) => boolean): EmailEventHandler<T, Event> {
  69. this.filterFns.push(filterFn);
  70. return this;
  71. }
  72. /**
  73. * @description
  74. * A function which defines how the recipient email address should be extracted from the incoming event.
  75. */
  76. setRecipient(setRecipientFn: (event: Event) => string): EmailEventHandler<T, Event> {
  77. this.setRecipientFn = setRecipientFn;
  78. return this;
  79. }
  80. /**
  81. * @description
  82. * A function which returns an object hash of variables which will be made available to the Handlebars template
  83. * and subject line for interpolation.
  84. */
  85. setTemplateVars(templateVarsFn: SetTemplateVarsFn<Event>): EmailEventHandler<T, Event> {
  86. this.setTemplateVarsFn = templateVarsFn;
  87. return this;
  88. }
  89. /**
  90. * @description
  91. * Sets the default subject of the email. The subject string may use Handlebars variables defined by the
  92. * setTemplateVars() method.
  93. */
  94. setSubject(defaultSubject: string): EmailEventHandler<T, Event> {
  95. this.defaultSubject = defaultSubject;
  96. return this;
  97. }
  98. /**
  99. * @description
  100. * Sets the default from field of the email. The from string may use Handlebars variables defined by the
  101. * setTemplateVars() method.
  102. */
  103. setFrom(from: string): EmailEventHandler<T, Event> {
  104. this.from = from;
  105. return this;
  106. }
  107. /**
  108. * @description
  109. * Add configuration for another template other than the default `"body.hbs"`. Use this method to define specific
  110. * templates for channels or languageCodes other than the default.
  111. */
  112. addTemplate(config: EmailTemplateConfig): EmailEventHandler<T, Event> {
  113. this.configurations.push(config);
  114. return this;
  115. }
  116. /**
  117. * @description
  118. * Allows data to be loaded asynchronously which can then be used as template variables.
  119. * The `loadDataFn` has access to the event, the TypeORM `Connection` object, and an
  120. * `inject()` function which can be used to inject any of the providers exported
  121. * by the {@link PluginCommonModule}. The return value of the `loadDataFn` will be
  122. * added to the `event` as the `data` property.
  123. *
  124. * @example
  125. * ```TypeScript
  126. * new EmailEventListener('order-confirmation')
  127. * .on(OrderStateTransitionEvent)
  128. * .filter(event => event.toState === 'PaymentSettled' && !!event.order.customer)
  129. * .loadData(({ event, inject}) => {
  130. * const orderService = inject(OrderService);
  131. * return orderService.getOrderPayments(event.order.id);
  132. * })
  133. * .setTemplateVars(event => ({
  134. * order: event.order,
  135. * payments: event.data,
  136. * }));
  137. * ```
  138. */
  139. loadData<R>(
  140. loadDataFn: LoadDataFn<Event, R>,
  141. ): EmailEventHandlerWithAsyncData<R, T, Event, EventWithAsyncData<Event, R>> {
  142. const asyncHandler = new EmailEventHandlerWithAsyncData(loadDataFn, this.listener, this.event);
  143. asyncHandler.setRecipientFn = this.setRecipientFn;
  144. asyncHandler.setTemplateVarsFn = this.setTemplateVarsFn;
  145. asyncHandler.filterFns = this.filterFns;
  146. asyncHandler.configurations = this.configurations;
  147. asyncHandler.defaultSubject = this.defaultSubject;
  148. asyncHandler.from = this.from;
  149. asyncHandler._mockEvent = this._mockEvent as any;
  150. return asyncHandler;
  151. }
  152. /**
  153. * @description
  154. * Used internally by the EmailPlugin to handle incoming events.
  155. *
  156. * @internal
  157. */
  158. async handle(
  159. event: Event,
  160. globals: { [key: string]: any } = {},
  161. injector: Injector,
  162. ): Promise<IntermediateEmailDetails | undefined> {
  163. for (const filterFn of this.filterFns) {
  164. if (!filterFn(event)) {
  165. return;
  166. }
  167. }
  168. if (this instanceof EmailEventHandlerWithAsyncData) {
  169. try {
  170. (event as EventWithAsyncData<Event, any>).data = await this._loadDataFn({
  171. event,
  172. injector,
  173. });
  174. } catch (err: unknown) {
  175. if (err instanceof Error) {
  176. Logger.error(err.message, loggerCtx, err.stack);
  177. } else {
  178. Logger.error(String(err), loggerCtx);
  179. }
  180. return;
  181. }
  182. }
  183. if (!this.setRecipientFn) {
  184. throw new Error(
  185. `No setRecipientFn has been defined. ` +
  186. `Remember to call ".setRecipient()" when setting up the EmailEventHandler for ${this.type}`,
  187. );
  188. }
  189. if (this.from === undefined) {
  190. throw new Error(
  191. `No from field has been defined. ` +
  192. `Remember to call ".setFrom()" when setting up the EmailEventHandler for ${this.type}`,
  193. );
  194. }
  195. const { ctx } = event;
  196. const configuration = this.getBestConfiguration(ctx.channel.code, ctx.languageCode);
  197. const subject = configuration ? configuration.subject : this.defaultSubject;
  198. if (subject == null) {
  199. throw new Error(
  200. `No subject field has been defined. ` +
  201. `Remember to call ".setSubject()" when setting up the EmailEventHandler for ${this.type}`,
  202. );
  203. }
  204. const recipient = this.setRecipientFn(event);
  205. const templateVars = this.setTemplateVarsFn ? this.setTemplateVarsFn(event, globals) : {};
  206. return {
  207. type: this.type,
  208. recipient,
  209. from: this.from,
  210. templateVars: { ...globals, ...templateVars },
  211. subject,
  212. templateFile: configuration ? configuration.templateFile : 'body.hbs',
  213. };
  214. }
  215. /**
  216. * @description
  217. * Optionally define a mock Event which is used by the dev mode mailbox app for generating mock emails
  218. * from this handler, which is useful when developing the email templates.
  219. */
  220. setMockEvent(event: Omit<Event, 'ctx' | 'data'>): EmailEventHandler<T, Event> {
  221. this._mockEvent = event;
  222. return this;
  223. }
  224. private getBestConfiguration(
  225. channelCode: string,
  226. languageCode: LanguageCode,
  227. ): EmailTemplateConfig | undefined {
  228. if (this.configurations.length === 0) {
  229. return;
  230. }
  231. const exactMatch = this.configurations.find(c => {
  232. return (
  233. (c.channelCode === channelCode || c.channelCode === 'default') &&
  234. c.languageCode === languageCode
  235. );
  236. });
  237. if (exactMatch) {
  238. return exactMatch;
  239. }
  240. const channelMatch = this.configurations.find(
  241. c => c.channelCode === channelCode && c.languageCode === 'default',
  242. );
  243. if (channelMatch) {
  244. return channelMatch;
  245. }
  246. return;
  247. }
  248. }
  249. /**
  250. * @description
  251. * Identical to the {@link EmailEventHandler} but with a `data` property added to the `event` based on the result
  252. * of the `.loadData()` function.
  253. *
  254. * @docsCategory EmailPlugin
  255. */
  256. export class EmailEventHandlerWithAsyncData<
  257. Data,
  258. T extends string = string,
  259. InputEvent extends EventWithContext = EventWithContext,
  260. Event extends EventWithAsyncData<InputEvent, Data> = EventWithAsyncData<InputEvent, Data>
  261. > extends EmailEventHandler<T, Event> {
  262. constructor(
  263. public _loadDataFn: LoadDataFn<InputEvent, Data>,
  264. listener: EmailEventListener<T>,
  265. event: Type<InputEvent>,
  266. ) {
  267. super(listener, event as any);
  268. }
  269. }