event-handler.ts 9.6 KB

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