From 5612c3f81f6b06f0c25559ccfd17a6ca34d8d467 Mon Sep 17 00:00:00 2001 From: giancarlo Date: Thu, 4 Apr 2024 16:27:02 +0800 Subject: [PATCH] Implement environment-based dynamic mailer switching This commit has modified the mailer system to allow flexible mailer selection according to the environment variable. Previously, it was set to use only 'Nodemailer' irrespective of the environment. Now, it has the ability to switch between 'Nodemailer' and 'CloudflareMailer' depending on the environment, facilitating better testing in diverse conditions. --- packages/mailers/src/index.ts | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/packages/mailers/src/index.ts b/packages/mailers/src/index.ts index 6765d1206..bc8cdef28 100644 --- a/packages/mailers/src/index.ts +++ b/packages/mailers/src/index.ts @@ -1,4 +1,9 @@ -import { Nodemailer } from './impl/nodemailer'; +import { z } from 'zod'; + +const MAILER_ENV = z + .enum(['nodemailer', 'cloudflare']) + .default('nodemailer') + .parse(process.env.MAILER_ENV); /** * @description A mailer interface that can be implemented by any mailer. @@ -16,4 +21,26 @@ import { Nodemailer } from './impl/nodemailer'; * text: 'Hello, World!' * }); */ -export const Mailer = Nodemailer; +export const Mailer = await getMailer(); + +/** + * @description Get the mailer based on the environment variable. + */ +async function getMailer() { + switch (MAILER_ENV) { + case 'nodemailer': { + const { Nodemailer } = await import('./impl/nodemailer'); + + return new Nodemailer(); + } + + case 'cloudflare': { + const { CloudflareMailer } = await import('./impl/cloudflare'); + + return new CloudflareMailer(); + } + + default: + throw new Error(`Invalid mailer environment: ${MAILER_ENV as string}`); + } +}