Added task queue for emails

This commit is contained in:
Jori Lallo
2017-12-18 20:47:48 -08:00
parent 7af2ff20a8
commit 1cb00079da
5 changed files with 168 additions and 17 deletions

View File

@@ -2,8 +2,8 @@
import React from 'react';
import nodemailer from 'nodemailer';
import Oy from 'oy-vey';
import Queue from 'bull';
import { baseStyles } from './emails/components/EmailLayout';
import { WelcomeEmail, welcomeEmailText } from './emails/WelcomeEmail';
type SendMailType = {
@@ -54,13 +54,14 @@ class Mailer {
});
} catch (e) {
Bugsnag.notifyException(e);
throw e; // Re-throw for queue to re-try
}
}
};
welcome = async (to: string) => {
welcome = async (opts: { to: string }) => {
this.sendMail({
to,
to: opts.to,
title: 'Welcome to Outline',
previewText:
'Outline is a place for your team to build and share knowledge.',
@@ -87,6 +88,30 @@ class Mailer {
}
const mailer = new Mailer();
const mailerQueue = new Queue('email', process.env.REDIS_URL);
export { Mailer };
export default mailer;
mailerQueue.process(async function(job) {
// $FlowIssue flow doesn't like dynamic values
await mailer[job.data.type](job.data.opts);
});
const sendEmail = (type: string, to: string, options?: Object = {}) => {
mailerQueue.add(
{
type,
opts: {
to,
...options,
},
},
{
attempts: 5,
backoff: {
type: 'exponential',
delay: 60 * 1000,
},
}
);
};
export { Mailer, mailerQueue, sendEmail };

View File

@@ -15,7 +15,7 @@ describe('Mailer', () => {
});
test('#welcome', () => {
fakeMailer.welcome('user@example.com');
fakeMailer.welcome({ to: 'user@example.com' });
expect(sendMailOutput).toMatchSnapshot();
});
});

View File

@@ -4,7 +4,7 @@ import bcrypt from 'bcrypt';
import uuid from 'uuid';
import { DataTypes, sequelize, encryptedFields } from '../sequelize';
import { uploadToS3FromUrl } from '../utils/s3';
import mailer from '../mailer';
import { sendEmail } from '../mailer';
import JWT from 'jsonwebtoken';
@@ -100,6 +100,6 @@ const hashPassword = function hashPassword(model) {
User.beforeCreate(hashPassword);
User.beforeUpdate(hashPassword);
User.beforeCreate(setRandomJwtSecret);
User.afterCreate(user => mailer.welcome(user.email));
User.afterCreate(user => sendEmail('welcome', user.email));
export default User;