Sunday 21 May 2017

Sequelize Instance method save() concurrency behaviour

This might be a bit of a silly question but if I have 2 API endpoints and a basic Sequelize model like so:

var User = storage.database.define('user', {
  email: {
    type: sql.STRING,
    validate: {
      isEmail: true,
    },
  },
  data: sql.JSON,
}, {
  freezeTableName: true,
  timestamps: true,
  hooks: {
    beforeUpdate: user => {
      user.set('data', user.data)
    },
  },
})

function getUser(email) {
  return User.findOne({
    where: { email },
  }).then(function(user) {
    if (!user) {
      throw {error: 'Unknown User'}
    }
    return user
  })
}

api.get('/one/:email', function(req, res, next) {
   getUser(req.params.email)
      .then(user => {
         user.data.someField = 1234;
         setTimeout(() => {
            user.save()
         }, 1000)
         res.send('one')
      })
})

api.get('/two/:email', function(req, res, next) {
   getUser(req.params.email)
      .then(user => {
         // update a different data field and/or the same field as in `one`
         user.data = { otherField: 'updated it', someField: 9999 };
         user.save()
         res.send('two')
      })
})

What happens if the same user sends 2 requests (one to each)? Will one override the other? If so, what happens if in two I don't set someField and instead just change the otherField and save it. Will the data set in one be lost?

If data is overridden, what is the recommended way to work with Sequelize Instances and update fields such as data without overriding data sent in other requests?



via FergusThePlant

No comments:

Post a Comment