Created
April 10, 2018 20:45
-
-
Save rafaelhdr/6ba630b57483670b9f4f7b67a483a074 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
'use latest'; | |
import sendgrid from 'sendgrid'; | |
import { MongoClient } from 'mongodb'; | |
const helper = sendgrid.mail; | |
const collection = 'users'; | |
/** | |
* @param context {WebtaskContext} | |
*/ | |
const sendReminder = function(context, cb, user) { | |
const { SENDGRID_API_KEY, FORM_ACTION, FROM_EMAIL } = context.secrets; | |
var from_email = FROM_EMAIL; | |
var to_email = user.email; | |
var username = user.username; | |
var subject = 'What did you do for your goal today?'; | |
var content = `<form method="POST" action="` + FORM_ACTION + `"> | |
<h1>What did you do for your goal today?</h1> | |
<input type="hidden" name="user" value="` + username + `" /> | |
I did: <input type="text" name="task" /> | |
<button type="submit" name="accomplished" value="1">Send</button> | |
<br /> | |
<br /> | |
<button type="submit" name="accomplished" value="0">Nothing :(</button> | |
</form> | |
<p> | |
Inspiration: | |
<a href="https://medium.com/the-mission/8-things-every-person-should-do-before-8-a-m-2183b7178b17">https://medium.com/the-mission/8-things-every-person-should-do-before-8-a-m-2183b7178b17</a> | |
</p> | |
` | |
const mail = new helper.Mail( | |
new helper.Email(from_email), | |
subject, | |
new helper.Email(to_email), | |
new helper.Content('text/html', content) | |
); | |
const sg = sendgrid(SENDGRID_API_KEY); | |
const request = sg.emptyRequest({ | |
method: 'POST', | |
path: '/v3/mail/send', | |
body: mail.toJSON() | |
}); | |
sg.API(request) | |
.then(response => cb(null, response)) | |
.catch(cb); | |
}; | |
module.exports = (context, cb) => { | |
const { MONGO_URL, SENDGRID_API_KEY } = context.secrets; | |
MongoClient.connect(MONGO_URL, (err, client) => { | |
const db = client.db("goal-reminder"); | |
if (err) return next(err); | |
db.collection(collection).find().toArray((err, users) => { | |
client.close(); | |
if (err) { | |
// TODO: Warn admin about error | |
return; | |
} | |
users.forEach(function(user) { | |
sendReminder(context, cb, user); | |
}); | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment