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.
This commit is contained in:
giancarlo
2024-04-04 16:27:02 +08:00
parent a52c8dd31c
commit 5612c3f81f

View File

@@ -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}`);
}
}