Skip to content

Instantly share code, notes, and snippets.

@sungwoncho
Created July 27, 2016 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sungwoncho/feda50c774d35d89513e1c581ad4e637 to your computer and use it in GitHub Desktop.
Save sungwoncho/feda50c774d35d89513e1c581ad4e637 to your computer and use it in GitHub Desktop.
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