帆交易僵局

时间:2019-01-25 14:56:12

标签: node.js transactions sails.js deadlock

当前,我正在开发 Sails 1.1.0 下的应用。 接下来,您可以查找代码何时抛出死锁

基本上,它与用户访问web_url有关,该Web_url为他创建了Token和UnassignedGame模型。在创建过程中,我收到了  有时在驱动程序MySQL中会出现DeadLock。

请告诉我是否出现任何错误,或者最终找到更好的版本或更好的处理方式。

谢谢

Token.js

module.exports = {
  attributes: {
    exp: {
      type: 'ref',
      columnType: 'datetime',
      required: true
    },
    value: {
      type: 'string',
      required: true
    },
    unassignedGame: {
      model: 'unassignedgame',
    }
  },
};

UnassignedGame.js

module.exports = {
  attributes: {
    score: {
      type: 'number',
      required: true
    },
    token: {
      model: 'token',
    }
  },
};

控制器

var flaverr = require('flaverr');

module.exports = {

  fn: async function (req, res) {
    let slug = this.req.param("slug");
    let token = this.req.param("token");
    var currentDateMoment = sails.moment.utc(new Date);
    currentDateMoment.add(2, 'h');
    let expirationDate = new Date(currentDateMoment.valueOf());
    var newToken = null;
    var newUnassignedGame = null;

    try {
      await sails.getDatastore().transaction(async (db) => {
        newToken = await Token.create({ exp: expirationDate, value: token }).usingConnection(db).fetch();
        if (!newToken) {
          throw flaverr('E_CANT_CREATE_TOKEN');
        } else {
          newUnassignedGame = await UnassignedGame.create({ score: 0, token: newToken.id }).usingConnection(db).fetch();
          if (!newUnassignedGame) {
            newToken = null;
            throw flaverr('E_CANT_CREATE_UNASSIGNED_GAME');
          }
        }
      }).intercept(
        [
          'E_CANT_CREATE_TOKEN',
          'E_CANT_CREATE_UNASSIGNED_GAME'
        ], () => 'E_FAILED_START'
      )
    } catch (err) {
      if (err.raw == "E_FAILED_START") {
        return this.res.redirect('/');
      } else {
        throw err;
      }
    }
    if (newToken != null && newUnassignedGame != null) {
      let tokenUpdated = await Token.update({ value: token }).set({ unassignedGame: newUnassignedGame.id }).fetch();
      if (!tokenUpdated) {
        return this.res.redirect('/');
      }
    }
    return this.res.view('game');
  }
}

0 个答案:

没有答案