Skip to content

Instantly share code, notes, and snippets.

@KendraTang
Created July 2, 2018 18:02
Show Gist options
  • Save KendraTang/297fda2b3743d16be7d16d7c34de15a1 to your computer and use it in GitHub Desktop.
Save KendraTang/297fda2b3743d16be7d16d7c34de15a1 to your computer and use it in GitHub Desktop.
const CardDB = require('../sql/card/CardDB.js')
CardDB.setSequelize(global.sequelize)
const CardModel = CardDB.model()
const ERROR = require('../const/error.js')
const ACTION = {
SELECT_VALID: 'SELECT_VALID',
UPDATE: 'UPDATE'
}
const sleep = (second) => {
return new Promise(resolve => setTimeout(resolve, second * 1000))
}
module.exports = class CardController {
handle (event, callback) {
const { value, action } = event
switch (action) {
case ACTION.SELECT_VALID:
global.sequelize.transaction({
autocommit: false
},
(t) => {
return CardModel
.findOne({
where: { status: 'valid' },
transaction: t,
lock: t.LOCK.UPDATE
})
.then(async card => {
console.log('selected?')
await sleep(10)
if (card) {
return card
.updateAttributes({ status: 'pending' }, { transaction: t })
.then(() => {
console.log('updated?')
callback(null, { card: card.dataValues })
})
.catch(callback)
} else {
callback(new Error('out of valid cards'))
}
})
.catch(error => {
callback(error)
})
})
break
case ACTION.UPDATE: {
const cardParameter = value.card
if (!cardParameter) {
const error = `card ${ERROR.OBJECT_IS_NOT_VALID}`
callback(error)
return
}
CardModel.findOne({
where: { id: cardParameter.id }
})
.then(card => {
if (card) {
card
.updateAttributes(cardParameter)
.then(() => {
callback(null, card)
})
.catch(error => {
callback(error)
})
} else {
callback(new Error('no resource'))
}
})
.catch(error => {
callback(error)
})
break
}
default:
throw new Error(`Invalid action type for ${this.constructor.name}`)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment