Created
September 13, 2020 14:11
-
-
Save dylansalim3/c2efeed74a4f46de17f812e8cc1e275a to your computer and use it in GitHub Desktop.
Sequelize Transaction sample
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
const t = await db.sequelize.transaction(); | |
const promises = []; | |
for (let i = 0; i < usersData.length; i++) { | |
promises[i] = UserRepository.createUser(usersData[i], {transaction: t}); | |
} | |
Promise.all(promises).then(users => { | |
const userRolePromises = []; | |
for (let i = 0; i < users.length; i++) { | |
userRolePromises.push(RoleRepository.findRoleById(rows[users[i].email]).then(role => { | |
users[i].addRole(role); | |
return users[i]; | |
})); | |
} | |
return Promise.all(userRolePromises); | |
}).then(function (users) { | |
let emailPromises = []; | |
users.forEach(user => { | |
const email = user.email; | |
const verification_hash = user.verification_hash; | |
const registrationLink = registrationLinkPrefix + '/' + verification_hash; | |
const {subject, text} = buildVerificationEmail(email, registrationLink); | |
emailPromises.push(sendEmail(email, subject, text, res)); | |
}); | |
return Promise.all(emailPromises); | |
}).then((result) => { | |
t.commit(); | |
res.send(result); | |
}).catch(function (err) { | |
t.rollback(); | |
console.log(err); | |
// t.rollback(); | |
return res.status(400).json({error: err.toString}); | |
// res.status(400).json({ message: errMessage }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment