BulkFindOrCreate and create with relationships: how?

40 views
Skip to first unread message

Tiago Cardoso

unread,
Mar 21, 2017, 12:11:08 PM3/21/17
to Sequelize
I'm trying to model an invitation model transaction for my use case, where I need to:

* find or create multiple users by email (in which new accounts are pending)
* Create an invitation for each

The documentation hasn't helped me find the best way to fit this all into a transaction, as what I'm doing right now is roughtly:

# email and inviter defined before
let nInvitations = emails.length
let invitations = []
emails.forEach((email) => {
  User.findOrCreate({ where: {email: email}})
    .then((user) => {
       let invitation = Invitation.build()
       invitation.setInviter(inviter)
       invitation.setInvitee(user)
       invitation.save()
         .then((invitation) => {
            invitations.push(invitation)
            if (invitations.length == nInvitations) {
               // uhf, where done
            }
         })
   })
})

There are many issues with my beautiful pyramid, but let's start with the obvious: iterating and creating each user is an obvious smell, as it is not transactionable and is inneficient (N INSERTs worst case scenario), and it gets intermangled with the invitation creation, which has to resort to using setters because I haven't found the way to use Invitation.create(...) which accepts relationships. 

I assume that my last question might be easier to solve. But a way to do a "bulk find or create" would be ideal to solve my issue. 

Is there already a way to cleanly do this?
Reply all
Reply to author
Forward
0 new messages