UNPKG

@websolutespa/payload-plugin-bowl

Version:

Bowl PayloadCms plugin of the BOM Repository

84 lines (83 loc) 3.4 kB
import { options } from '../../options'; /** * Sends an email based on the provided request and email configuration. * * @param req - The PayloadRequest object containing the request details. * @param action - The action key used to retrieve the email configuration. * @param callback - A callback function to modify the SendMailOptions before sending the email. * * The function performs the following steps: * 1. Extracts email data from the request body. * 2. Iterates over each email data entry. * 3. If an ID is provided in the email data, retrieves the corresponding email configuration. * 4. If no ID is provided, checks if there is an email configuration associated with the action key. * 5. Constructs the email options by merging the email data and email configuration. * 6. Applies the callback function to modify the email options if provided. * 7. Sends the email asynchronously using the payload's sendEmail method. * * @throws Will log an error message if sending the email fails. */ export async function sendEmail(req, action, callback) { const { payload, data = {} } = req; const { emailData = [] } = data; for (const email of emailData){ try { const { id, ...emailRest } = email; let emailConfig = undefined; if (id) { /** * if id is provided, retrieve the email config */ emailConfig = await payload.findByID({ collection: options.slug.emailConfig, id: id, req: req, overrideAccess: true }); } else { /** * check if exist an email config associated to the action */ const emailConfigs = await payload.find({ collection: options.slug.emailConfig, where: { action: { equals: action } }, req: req, overrideAccess: true }); if (emailConfigs.totalDocs > 0) { emailConfig = emailConfigs.docs[0]; } } const recipientKeys = [ 'to', 'cc', 'bcc' ]; const emailConfigOptions = emailConfig ? Object.fromEntries(Object.entries(emailConfig).filter((kv)=>{ return recipientKeys.includes(kv[0]) ? kv[1].length > 0 : true; }).map((kv)=>{ if (recipientKeys.includes(kv[0])) { kv[1] = kv[1].map((x)=>x.address).join(','); } return kv; })) : {}; /** * existing emailConfig options overrides mixerConfig values */ let emailOptions = { ...emailRest, ...emailConfigOptions }; if (typeof callback === 'function') { emailOptions = callback(emailOptions); } /** * we are not awaiting here for sendEmail promise * send email is async after return */ payload.sendEmail(emailOptions); } catch (error) { console.log('EmailService.sendEmail.error', error?.statusText); } } } //# sourceMappingURL=email.service.js.map