Skip to content

Commit

Permalink
fix job sending
Browse files Browse the repository at this point in the history
  • Loading branch information
mjlescano committed Jun 25, 2017
1 parent f5783c9 commit 5fab643
Show file tree
Hide file tree
Showing 18 changed files with 127 additions and 61 deletions.
34 changes: 23 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Graceful = require('node-graceful')
const pify = require('pify')
const config = require('./lib/config')

// Load translations
Expand All @@ -17,12 +18,24 @@ const notifier = module.exports = {}
notifier.init = function init () {
return Promise.all([
require('./lib/db'),
require('./lib/mailer'),
require('./lib/agenda')
]).then(([db, agenda]) => {
]).then(([db, mailer, agenda]) => {
notifier.db = db
notifier.mailer = mailer
notifier.agenda = agenda

return notifier
/**
* Promisified verions of Agenda#every, Agenda#schedule and
* Agenda#now methods
*/
;['every', 'schedule', 'now'].forEach((method) => {
notifier[method] = pify(agenda[method].bind(agenda))
})

return Promise.resolve(notifier)
}).then((notifier) => {
return require('./lib/jobs').init(notifier)
}).catch((err) => { throw err })
}

Expand All @@ -35,15 +48,13 @@ notifier.init = function init () {
*/

notifier.start = function start () {
return notifier.init()
.then(require('./lib/agenda'))
.then((agenda) => {
agenda.start()
Graceful.on('exit', () => agenda.stop())
return notifier.init().then(() => {
notifier.agenda.start()

return notifier
})
.catch((err) => { throw err })
Graceful.on('exit', () => notifier.agenda.stop())

return Promise.resolve(notifier)
}).catch((err) => { throw err })
}

/**
Expand Down Expand Up @@ -71,7 +82,8 @@ notifier.agenda = null

/**
* Email sender utility
* Will be defined after the call of init()
* @return {Mailer}
*/

notifier.mailer = require('./lib/mailer')
notifier.mailer = null
11 changes: 9 additions & 2 deletions lib/agenda/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
const Agenda = require('agenda')
const Graceful = require('node-graceful')
const config = require('../config')
const connection = require('../db/connection')

module.exports = connection.then((conn) => {
module.exports = connection.then((db) => {
return new Promise((resolve, reject) => {
const agenda = new Agenda({ mongo: conn })
const agenda = new Agenda({
mongo: db,
db: { collection: config.get('collection') }
})

agenda.on('error', reject)
agenda.on('ready', () => resolve(agenda))

Graceful.on('exit', (done) => agenda.stop(done))
})
}).catch((err) => { throw err })
4 changes: 2 additions & 2 deletions lib/config/defaults.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
"ru",
"uk"
],
"organizationName": "[email protected]",
"organizationEmail": "The DemocracyOS team",
"organizationName": "The DemocracyOS team",
"organizationEmail": "[email protected]",
"mailer": {
"service": "",
"auth": {
Expand Down
4 changes: 2 additions & 2 deletions lib/db/connection.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const db = require('.')

module.exports = db.then(() => {
module.exports = db.then((db) => {
return db._db
})
}).catch((err) => { throw err })
23 changes: 21 additions & 2 deletions lib/db/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,26 @@
const monk = require('monk')
const Graceful = require('node-graceful')
const listenOnceOf = require('../utils/listen-once-of')
const config = require('../config')

const db = module.exports = monk(config.get('mongoUrl'))
module.exports = monk(config.get('mongoUrl')).then((db) => {
db.catch = db.then = new Promise((resolve, reject) => {
switch (db._state) {
case 'closed':
reject(new Error('Connection closed'))
break
case 'open':
resolve(db)
break
default:
listenOnceOf(db, {
open: resolve,
'error-opening': reject
})
}
})

Graceful.on('exit', () => db.close())
Graceful.on('exit', (done) => db.close(done))

return db
}).catch((err) => { throw err })
8 changes: 6 additions & 2 deletions lib/jobs/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
var path = require('path')
var requireAll = require('require-all')

module.exports.init = function init () {
const jobs = requireAll(path.join(__dirname, '/lib'))
module.exports.init = function init (notifier) {
const jobs = requireAll({
dirname: path.join(__dirname, '/lib'),
resolve: (job) => typeof job === 'function' && job(notifier)
})

return Promise.all(Object.keys(jobs).map((name) => jobs[name]))
}
15 changes: 9 additions & 6 deletions lib/jobs/lib/forgot-password.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,18 @@ const mailer = require('../../mailer')
const jobName = 'forgot-password'
const template = templates[jobName]

module.exports = Promise.all([
require('../../db').get('users'),
require('../../agenda')
]).then(([users, agenda]) => {
module.exports = function forgotPassword (notifier) {
const { db, agenda } = notifier
const users = db.get('users')

agenda.define(jobName, (job, done) => {
const data = job.attrs.data

users.findOne({ email: data.to }).then((user) => {
if (!user) throw new Error(`User not found for email "${data.email}"`)
if (!user) {
const err = new Error(`User not found for email "${data.to}"`)
return done(err)
}

return mailer.send({
to: utils.emailAddress(user),
Expand All @@ -28,4 +31,4 @@ module.exports = Promise.all([
})
}).then(done).catch(done)
})
}).catch((err) => { throw err })
}
10 changes: 5 additions & 5 deletions lib/jobs/lib/topic-published.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ const utils = require('../../utils')
const jobName = 'topic-published'
const jobNameForSingleUser = 'topic-published-single-recipient'

module.exports = Promise.all([
require('../../db').get('users'),
require('../../agenda')
]).then(([users, agenda]) => {
module.exports = function topicPublished (notifier) {
const { db, agenda } = notifier
const users = db.get('users')

agenda.define(jobName, (job, done) => {
const data = job.attrs.data

Expand All @@ -25,4 +25,4 @@ module.exports = Promise.all([
done()
}).catch(done)
})
}).catch((err) => { throw err })
}
17 changes: 10 additions & 7 deletions lib/jobs/lib/welcome-email.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ const mailer = require('../../mailer')
const jobName = 'welcome-email'
const template = templates[jobName]

module.exports = Promise.all([
require('../../db').get('users'),
require('../../agenda')
]).then(([users, agenda]) => {
module.exports = function welcomeEmail (notifier) {
const { db, agenda } = notifier
const users = db.get('users')

agenda.define(jobName, { priority: 'high' }, welcomeEmailJob)
agenda.define('signup', { priority: 'high' }, welcomeEmailJob)
agenda.define('resend-validation', { priority: 'high' }, welcomeEmailJob)
Expand All @@ -18,7 +18,10 @@ module.exports = Promise.all([
const data = job.attrs.data

users.findOne({ email: data.to }).then((user) => {
if (!user) throw new Error(`User not found for email "${data.email}"`)
if (!user) {
const err = new Error(`User not found for email "${data.to}"`)
return done(err)
}

const html = template({
USER_NAME: user.firstName,
Expand All @@ -32,6 +35,6 @@ module.exports = Promise.all([
subject: t(`templates.${jobName}.subject`),
html
})
}).catch(done)
}).then(done).catch(done)
}
}).catch((err) => { throw err })
}
23 changes: 10 additions & 13 deletions lib/mailer/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
const pify = require('pify')
const config = require('../config')
const transporter = require('./transporter')

module.exports.send = function send (opts) {
return new Promise((resolve, reject) => {
if (!opts.from) {
opts.from = {
name: config.get('organizationName'),
address: config.get('organizationEmail')
}
}
const sendMail = pify(transporter.sendMail.bind(transporter))

const defaultSender = {
name: config.get('organizationName'),
address: config.get('organizationEmail')
}

transporter.sendMail(opts, (err) => {
if (err) return reject(err)
resolve()
})
})
module.exports.send = function send (opts) {
if (!opts.from) opts.from = defaultSender
return sendMail(opts)
}
2 changes: 1 addition & 1 deletion lib/templates/lib/comment-reply.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ module.exports = function welcomeEmail (vars, opts) {
<p>${vars.reply}</p>
<p>${raw(_t('templates.comment-reply.body2'))}</p>
<p>${_t('templates.email.signature')}</p>
`
`.toString()
}
2 changes: 1 addition & 1 deletion lib/templates/lib/forgot-password.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ module.exports = function welcomeEmail (vars, opts) {
<p>${raw(_t('templates.forgot-password.body'))}</p>
<p>${_t('templates.email.signature')}</p>
<p>${_t('templates.forgot-password.ps')}</p>
`
`.toString()
}
2 changes: 1 addition & 1 deletion lib/templates/lib/topic-published.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ module.exports = function welcomeEmail (vars, opts) {
<p>${vars.topic}</p>
<p>${raw(_t('templates.topic-published.body2'))}</p>
<p>${_t('templates.email.signature')}</p>
`
`.toString()
}
3 changes: 2 additions & 1 deletion lib/templates/lib/welcome-email.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,11 @@ module.exports = function welcomeEmail (vars, opts) {
t.lang(opts.lang)
const _t = (key) => t(key, vars)

console.log(_t('templates.email.greeting'))
return html`
<p>${_t('templates.email.greeting')}</p>
<p>${raw(_t('templates.welcome-email.body'))}</p>
<p>${_t('templates.email.signature')}</p>
<p>${_t('templates.welcome-email.ps')}</p>
`
`.toString()
}
4 changes: 2 additions & 2 deletions lib/utils/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module.exports.emailAddress = function emailAddress (user) {
return {
address: user.email,
name: user.lastName ? user.firstName + ' ' + user.lastName : user.firstName
name: user.lastName ? user.firstName + ' ' + user.lastName : user.firstName,
address: user.email
}
}
19 changes: 19 additions & 0 deletions lib/utils/listen-once-of.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module.exports = function listenOnceOf (emitter, callbacks) {
const events = Object.keys(callbacks)
const listeners = {}

const removeListeners = () => {
events.forEach((event) => {
emitter.removeListener(event, listeners[event])
})
}

events.forEach((event) => {
const listener = listeners[event] = (...args) => {
removeListeners()
callbacks[event](...args)
}

emitter.once(event, listener)
})
}
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"monk": "~6.0.0",
"node-graceful": "~0.2.3",
"nodemailer": "~2.7.2",
"pify": "~3.0.0",
"require-all": "~2.1.0",
"t-component": "1.0.0"
},
Expand Down

0 comments on commit 5fab643

Please sign in to comment.