Last active
January 20, 2019 16:35
-
-
Save nateplusplus/ec5fee4e17001c54d40295bc9ca64d5b to your computer and use it in GitHub Desktop.
Using async and await with mysql2 package for node
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
require('dotenv').config(); | |
const db_creds = { | |
host : process.env.MYSQL_HOST || '', | |
user : process.env.MYSQL_USER || '', | |
password : process.env.MYSQL_PASSWORD || '', | |
dateStrings : true, | |
} | |
const mysql = require('mysql2'); | |
module.exports = { | |
/** | |
* Send email | |
* | |
* @return email object | |
**/ | |
"sendEmail": async function(req, res, next, notification) { | |
try { | |
var db = await mysql.createConnection(db_creds); | |
// Save email to database | |
const createEmail = `INSERT INTO system.notification | |
(to_user_id, email, template, template_data, type, created, created_by) | |
VALUES (?, ?, ?, ?, ?, NOW(), ?);`; | |
const emailValues = [ | |
notification.to_user_id, | |
notification.email, | |
templateData, | |
notification.template, | |
notification.type, | |
notification.createdBy | |
]; | |
const result = await db.execute(createEmail, emailValues); | |
console.log(result.insertId); // Returns 0 | |
// TODO: send email after successful save... | |
return result; | |
} catch (err) { | |
console.error(err.stack); | |
} | |
} | |
} |
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
// sendEmail is called within express app, something like this: | |
const Email = require('../models/Email'); | |
router.post('/', async (req, res, next) => { | |
const data = req.body; | |
var templateData = { | |
"subject" : data.subject, | |
"message" : data.message | |
}; | |
// Setup notification | |
try { | |
var notification = new Notification(user, { | |
"type" : 'message', | |
"template" : "Message", | |
"templateData" : templateData, | |
"createdBy": 0, | |
}); | |
} | |
catch(e) { | |
console.error(e); | |
} | |
// Save notification to database and other stuff... | |
let result = await Email.sendEmail(req, res, next, notification); | |
console.log(result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment