event-handler.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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, 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<
  160. | { from: string; recipient: string; templateVars: any; subject: string; templateFile: string }
  161. | undefined
  162. > {
  163. for (const filterFn of this.filterFns) {
  164. if (!filterFn(event)) {
  165. return;
  166. }
  167. }
  168. if (!this.setRecipientFn) {
  169. throw new Error(
  170. `No setRecipientFn has been defined. ` +
  171. `Remember to call ".setRecipient()" when setting up the EmailEventHandler for ${this.type}`,
  172. );
  173. }
  174. if (this.from === undefined) {
  175. throw new Error(
  176. `No from field has been defined. ` +
  177. `Remember to call ".setFrom()" when setting up the EmailEventHandler for ${this.type}`,
  178. );
  179. }
  180. const { ctx } = event;
  181. const configuration = this.getBestConfiguration(ctx.channel.code, ctx.languageCode);
  182. const subject = configuration ? configuration.subject : this.defaultSubject;
  183. if (subject == null) {
  184. throw new Error(
  185. `No subject field has been defined. ` +
  186. `Remember to call ".setSubject()" when setting up the EmailEventHandler for ${this.type}`,
  187. );
  188. }
  189. const recipient = this.setRecipientFn(event);
  190. const templateVars = this.setTemplateVarsFn ? this.setTemplateVarsFn(event, globals) : {};
  191. return {
  192. recipient,
  193. from: this.from,
  194. templateVars: { ...globals, ...templateVars },
  195. subject,
  196. templateFile: configuration ? configuration.templateFile : 'body.hbs',
  197. };
  198. }
  199. /**
  200. * @description
  201. * Optionally define a mock Event which is used by the dev mode mailbox app for generating mock emails
  202. * from this handler, which is useful when developing the email templates.
  203. */
  204. setMockEvent(event: Omit<Event, 'ctx'>): EmailEventHandler<T, Event> {
  205. this._mockEvent = event;
  206. return this;
  207. }
  208. private getBestConfiguration(
  209. channelCode: string,
  210. languageCode: LanguageCode,
  211. ): EmailTemplateConfig | undefined {
  212. if (this.configurations.length === 0) {
  213. return;
  214. }
  215. const exactMatch = this.configurations.find(c => {
  216. return (
  217. (c.channelCode === channelCode || c.channelCode === 'default') &&
  218. c.languageCode === languageCode
  219. );
  220. });
  221. if (exactMatch) {
  222. return exactMatch;
  223. }
  224. const channelMatch = this.configurations.find(
  225. c => c.channelCode === channelCode && c.languageCode === 'default',
  226. );
  227. if (channelMatch) {
  228. return channelMatch;
  229. }
  230. return;
  231. }
  232. }
  233. /**
  234. * @description
  235. * Identical to the {@link EmailEventHandler} but with a `data` property added to the `event` based on the result
  236. * of the `.loadData()` function.
  237. *
  238. * @docsCategory EmailPlugin
  239. */
  240. export class EmailEventHandlerWithAsyncData<
  241. Data,
  242. T extends string = string,
  243. InputEvent extends EventWithContext = EventWithContext,
  244. Event extends EventWithAsyncData<InputEvent, Data> = EventWithAsyncData<InputEvent, Data>
  245. > extends EmailEventHandler<T, Event> {
  246. constructor(
  247. public _loadDataFn: LoadDataFn<InputEvent, Data>,
  248. listener: EmailEventListener<T>,
  249. event: Type<InputEvent>,
  250. ) {
  251. super(listener, event as any);
  252. }
  253. }