From c480a4821a16817d953f36693d2ede0f90445d43 Mon Sep 17 00:00:00 2001 From: Dobromir Popov Date: Sat, 6 Apr 2024 11:10:12 +0300 Subject: [PATCH] optimize normalization --- src/helpers/email.js | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/src/helpers/email.js b/src/helpers/email.js index 8f5d2ff..0dff56a 100644 --- a/src/helpers/email.js +++ b/src/helpers/email.js @@ -58,35 +58,34 @@ function setResult(result) { exports.GetLastResult = function () { return lastResult; }; + function normalizeEmailAddresses(to) { - // If 'to' is already a string, it could be a single email or a CSV of emails + let emails = []; + if (typeof to === 'string') { - // Check if 'to' is a CSV string of emails; split it into an array if true - if (to.includes(',')) { - return to.split(/\s*,\s*/); // Split by comma and trim spaces around emails - } - // Otherwise, return it as a single-element array - return [to]; - } - - // If 'to' is an array, determine if it's an array of strings or objects - if (Array.isArray(to)) { - return to.map(item => { - // If the item is a string, return it directly + // Handle CSV string by splitting into an array + if (to.includes(',')) emails = to.split(/\s*,\s*/); + else emails = [to]; // Handle single email string + } else if (Array.isArray(to)) { + emails = to.map(item => { if (typeof item === 'string') return item; - // If the item is an object with name and email, format it if (item.name && item.email) return `"${item.name}" <${item.email}>`; - // If the item is an object but doesn't match expected structure, stringify it - return JSON.stringify(item); - }).join(', '); + return JSON.stringify(item); // Handle unexpected object format + }); + } else if (typeof to === 'object' && to.email) { + // Handle single object + emails = [`"${to.name}" <${to.email}>`]; + } else { + // Fallback for other types + emails = [String(to)]; } - // Fallback for any other types (unlikely but safe) - return String(to); + return emails; // Always returns an array } + + exports.SendEmail = async function (to, subject, text, html, attachments = []) { let sender = '"Специално Свидетелстване София - тест" '; - to = Array.isArray(to) ? to : [to]; const emailAddresses = normalizeEmailAddresses(to) const message = {