optimize normalization

This commit is contained in:
Dobromir Popov
2024-04-06 11:10:12 +03:00
parent fa786485c2
commit c480a4821a

View File

@ -58,35 +58,34 @@ function setResult(result) {
exports.GetLastResult = function () { exports.GetLastResult = function () {
return lastResult; return lastResult;
}; };
function normalizeEmailAddresses(to) { 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') { if (typeof to === 'string') {
// Check if 'to' is a CSV string of emails; split it into an array if true // Handle CSV string by splitting into an array
if (to.includes(',')) { if (to.includes(',')) emails = to.split(/\s*,\s*/);
return to.split(/\s*,\s*/); // Split by comma and trim spaces around emails else emails = [to]; // Handle single email string
} } else if (Array.isArray(to)) {
// Otherwise, return it as a single-element array emails = to.map(item => {
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
if (typeof item === 'string') return 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 (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); // Handle unexpected object format
return JSON.stringify(item); });
}).join(', '); } 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 emails; // Always returns an array
return String(to);
} }
exports.SendEmail = async function (to, subject, text, html, attachments = []) { exports.SendEmail = async function (to, subject, text, html, attachments = []) {
let sender = '"Специално Свидетелстване София - тест" <demo@mwitnessing.com>'; let sender = '"Специално Свидетелстване София - тест" <demo@mwitnessing.com>';
to = Array.isArray(to) ? to : [to];
const emailAddresses = normalizeEmailAddresses(to) const emailAddresses = normalizeEmailAddresses(to)
const message = { const message = {