UNPKG

@454creative/easy-email

Version:

A framework-agnostic email service library for Node.js with observability and monitoring

128 lines (112 loc) 3.17 kB
import { SmtpConfig, SendGridConfig, SesConfig, EmailProviderConfig, EmailProviderType, } from '../interfaces/email-options.interface'; export const DEFAULT_RETRY_ATTEMPTS = 3; export const DEFAULT_RETRY_DELAY = 1000; // 1 second export const DEFAULT_TIMEOUT = 10000; // 10 seconds export const DEFAULT_SMTP_CONFIG: SmtpConfig = { host: 'smtp.example.com', port: 587, secure: false, auth: { user: '', pass: '', }, tls: { rejectUnauthorized: true, }, }; export const DEFAULT_SENDGRID_CONFIG: SendGridConfig = { apiKey: '', }; /** * Default AWS SES Configuration */ export const DEFAULT_SES_CONFIG: SesConfig = { region: 'us-west-2', apiVersion: '2010-12-01', maxRetries: 3, httpOptions: { timeout: 10000, connectTimeout: 5000, }, }; export class EmailConfigBuilder { private config: EmailProviderConfig; private retryAttempts: number = DEFAULT_RETRY_ATTEMPTS; private retryDelay: number = DEFAULT_RETRY_DELAY; private timeout: number = DEFAULT_TIMEOUT; constructor(providerType: EmailProviderType = EmailProviderType.SMTP) { let defaultConfig: SmtpConfig | SendGridConfig | SesConfig; switch (providerType) { case EmailProviderType.SMTP: defaultConfig = { ...DEFAULT_SMTP_CONFIG }; break; case EmailProviderType.SENDGRID: defaultConfig = { ...DEFAULT_SENDGRID_CONFIG }; break; case EmailProviderType.SES: // AWS SES Configuration defaultConfig = { ...DEFAULT_SES_CONFIG }; break; default: defaultConfig = { ...DEFAULT_SMTP_CONFIG }; } this.config = { type: providerType, config: defaultConfig, }; } withSmtpConfig(config: Partial<SmtpConfig>): this { if (this.config.type !== EmailProviderType.SMTP) { throw new Error('Cannot set SMTP config for non-SMTP provider'); } this.config.config = { ...this.config.config, ...config } as SmtpConfig; return this; } withSendGridConfig(config: Partial<SendGridConfig>): this { if (this.config.type !== EmailProviderType.SENDGRID) { throw new Error('Cannot set SendGrid config for non-SendGrid provider'); } this.config.config = { ...this.config.config, ...config } as SendGridConfig; return this; } /** * Configure AWS SES settings */ withSesConfig(config: Partial<SesConfig>): this { if (this.config.type !== EmailProviderType.SES) { throw new Error('Cannot set SES config for non-SES provider'); } this.config.config = { ...this.config.config, ...config } as SesConfig; return this; } withRetryAttempts(attempts: number): this { this.retryAttempts = attempts; return this; } withRetryDelay(delay: number): this { this.retryDelay = delay; return this; } withTimeout(timeout: number): this { this.timeout = timeout; return this; } build(): EmailProviderConfig & { retryAttempts: number; retryDelay: number; timeout: number; } { return { ...this.config, retryAttempts: this.retryAttempts, retryDelay: this.retryDelay, timeout: this.timeout, }; } }