All files / lib/email email-provider.factory.ts

100% Statements 12/12
100% Branches 8/8
100% Functions 1/1
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57                                                        68x     68x 3x 3x           65x 46x 46x       19x 3x 3x       16x     16x    
import {
	ResendProvider,
	MailtrapProvider,
	MailpitProvider,
	MockProvider,
	type EmailProvider,
} from "./providers";
 
export type { EmailProvider };
 
export interface EmailFactoryConfig {
	resendApiKey?: string;
	mailtrapApiToken?: string;
	mailtrapInboxId?: string;
	mailpitHost?: string;
	fromEmail: string;
}
 
/**
 * Factory for creating email providers based on configuration
 *
 * Priority order:
 * 1. If MAILTRAP_API_TOKEN + MAILTRAP_INBOX_ID → Use Mailtrap (dev/preview sandbox)
 * 2. If RESEND_API_KEY is set → Use Resend (production)
 * 3. If MAILPIT_HOST is set → Use Mailpit (local testing)
 * 4. Otherwise → Use Mock (console logging)
 */
export function createEmailProvider(config: EmailFactoryConfig): EmailProvider {
	const { resendApiKey, mailtrapApiToken, mailtrapInboxId, mailpitHost, fromEmail } = config;
 
	// Priority 1: Mailtrap (dev/preview sandbox — no real delivery)
	if (mailtrapApiToken && mailtrapInboxId) {
		console.log("[EMAIL] Using Mailtrap sandbox provider");
		return new MailtrapProvider(mailtrapApiToken, mailtrapInboxId, {
			from: fromEmail,
		});
	}
 
	// Priority 2: Resend (production)
	if (resendApiKey) {
		console.log("[EMAIL] Using Resend provider");
		return new ResendProvider(resendApiKey, { from: fromEmail });
	}
 
	// Priority 3: Mailpit (local development)
	if (mailpitHost) {
		console.log(`[EMAIL] Using Mailpit provider at ${mailpitHost}:8025`);
		return new MailpitProvider(mailpitHost, { from: fromEmail });
	}
 
	// Priority 4: Mock (console logging)
	console.warn(
		"[EMAIL] No email provider configured - using mock (console logging)",
	);
	return new MockProvider();
}