Created
July 27, 2016 05:19
-
-
Save sungwoncho/feda50c774d35d89513e1c581ad4e637 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function sendJobAlertEmail() { | |
console.log('CRON: sending alert email'); | |
function handleJobs(jobs, user, notifiableJobs, done) { | |
each(jobs, (job, n) => { | |
Notification.count({ jobId: job._id, userId: user._id }, (err, count) => { | |
if (count > 0) { | |
console.log('notificaiton already sent'); | |
return n(); | |
} | |
console.log('job found', job.title); | |
notifiableJobs.push(job); | |
n(); | |
}); | |
}, done); | |
} | |
function handleCompanyIds(companyIds, user, notifiableJobs, done) { | |
each(companyIds, (companyId, n) => { | |
Job.find({ company: new ObjectId(companyId) }).populate('company').exec((err, jobs) => { | |
console.log('job count', jobs.length); | |
handleJobs(jobs, user, notifiableJobs, n); | |
}); | |
}, done); | |
} | |
function handleFollowings(followings, done) { | |
each(followings, (following, n) => { | |
const notifiableJobs = []; | |
User.findById(following.userId, (err, user) => { | |
if (!user.emailVerified) { | |
console.log('email not verified'); | |
return n(); | |
} | |
handleCompanyIds(following.companyIds, user, notifiableJobs, () => { | |
if (notifiableJobs.length === 0) { | |
console.log('No jobs to notify'); | |
return n(); | |
} | |
const mailOptions = buildEmail({ jobs: notifiableJobs, user }); | |
sendEmail(mailOptions, (err) => { | |
if (err) { | |
console.log('Error while sending job email', err); | |
return; | |
} | |
each(notifiableJobs, (notifiedJob, m) => { | |
let doc = new Notification({ jobId: notifiedJob._id, userId: user._id }); | |
doc.save(m); | |
}, n); | |
}); | |
}); | |
}); | |
}, done); | |
} | |
waterfall([ | |
(cb) => { | |
Following.find({}, cb); | |
}, | |
handleFollowings | |
], (err) => { | |
if (err) { | |
console.log('Error while sending job email', err); | |
} | |
console.log('done'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment