Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // should be outside, need to do it just once not everytime
- transporter.verify(function (error, success) {
- if (error) {
- console.log('Failed to connect to SMTP server');
- console.log(error);
- } else {
- console.log('Connected to SMTP server!');
- }
- });
- // promise wrapper to send email, so that we can use this function easily in async method easily later on:
- const sendEmailPromise = (mailOptions) => new Promise((resolve, reject) => {
- transporter.sendMail(mailOptions, async function (err, data) {
- // not rejecting in any scenario, if error is there just add err: True to result
- // this is because we are going to use it in Promise.all and if even one fails, Promise.all throws error which we dont want
- // attaching originalOptions just to log it later on if needed
- if (err) {
- resolve({ error: true, err: err, originalOptions: mailOptions });
- }
- else {
- resolve({ ...data, originalOptions: mailOptions });
- }
- });
- });
- exports.mailSend = catchAsyncErrors(async (req, res, next) => {
- const { list, buildId } = req.body;
- var rejected = 0; // should not be const, const value cannot change so ++rejected would not work actually
- const build = await Build.findById(buildId);
- if (!build) {
- return next(new ErrorHandler("Build not found", 404));
- }
- var mail_queue = [];
- list.forEach((item, index) => {
- const mailOptions = {
- // from: process.env.EMAIL,
- to: item.email,
- subject: "Invitation to Test",
- html: `<h1>You have Been Invited to Test an Application</h1><p>Click <a href='${req.protocol}://${process.env.REQ_HOST}/invites/${buildId}'>here</a> or visit your profile on <a href="${req.protocol}://${process.env.REQ_HOST}/profile">${req.protocol}://${process.env.REQ_HOST}/profile</a> to view.</p>`,
- };
- mail_queue.push(sendEmailPromise(mailOptions));
- });
- // now that we have pushed each email in array we actually need to wait for each to be finished, this is where we use Promise.all
- const mailResults = await Promise.all(mail_queue);
- // now we loop through mailResults and just see if err: true OR .rejected.length > 0 as you were checking
- mailResults.forEach((result, index) => {
- if (result.err || (result.rejected && result.rejected.length > 0)) {
- console.log("Failed to send eamil for", result.originalOptions);
- console.log(result);
- console.log(); // blank line for clarity in logs
- rejected++;
- }
- else {
- build.invites.push({ tester: item._id, status: "pending" });
- }
- });
- await build.save(); // save build
- if (rejected > 0)
- return next(
- new ErrorHandler(
- "A few testers didn't get invited. Check the invited list.",
- 417
- )
- );
- res.status(200).json({
- success: true,
- });
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement