chat program, the user can grab the vest. If two users grab the vest at the same time, both users will grab the vest. How can the first user block the table when operating the table?
how should I use transactions with logic like the following?
rob_vest: async function (data, socket) {
let vest_time = Date.now()
console.log("", vest_time)
let sequlize = await db
let phone = data.phone
let room = data.room
let url = data.url
//
let vest = await sequlize.models.user_vest.findOne({ where: { url: data.url, have_vest: 1, online: 1, room: room }, raw: true })
let cool_vest = await sequlize.models.used_vest.findOne({ where: { phone, room, url }, raw: true })
if (vest) {
io.sockets.connected[socket.id].emit("rob_vest", { success: false, message: "not avilable vest" })
return
}
//
if (!cool_vest) {
console.log("*userd_time", vest_time)
let used_time = vest_time
console.log("userddddddddtime------------------", used_time)
let data = await sequlize.models.used_vest.create({ phone, room, url, used_time })
} else {
let begin_time = cool_vest.used_time + 60 * 60 * 2 * 1000
let stop_time = begin_time + 60 * 60 * 2 * 1000
console.log(begin_time, vest_time, stop_time, "8989898989898", vest_time < stop_time && begin_time < vest_time)
if (begin_time < vest_time && vest_time < stop_time) {
io.sockets.connected[socket.id].emit("rob_vest", { success: false, msg: "" })
return
} else {
let used_time = vest_time
sequlize.models.used_vest.update({ used_time }, { where: { phone, room, url } })
}
}
//
let update_user = await sequlize.models.chat_user.update({ have_vest: 1, url: data.url, vest_name: data.vest_name, vest_time: vest_time, room: room }, { where: { phone }, raw: true })
// let update_vest = sequlize.models.chat_vest.update({ is_used: 1, used_time: vest_time }, { where: { url: data.url }, raw: true })
if (update_user) {
//
io.to(room).emit("rob_vest", { success: true, phone: phone })
schedules.addListenVest(io)
} else {
//
io.sockets.connected[socket.id].emit("rob_vest", { success: false, phone: phone })
}
}