Here's a booking function. It checks whether the room is free for the night, and if it is, it saves the booking.
async function book ( roomId : string , night : string , guest : string ) { const { rows } = await pool . query ( " SELECT count(*)::int AS taken FROM bookings WHERE room_id = $1 AND night = $2 " , [ roomId , night ], ); if ( rows [ 0 ]. taken > 0 ) return ` ${ guest } : sorry, already booked` ;
await pool . query ( " INSERT INTO bookings (room_id, night, guest) VALUES ($1, $2, $3) " , [ roomId , night , guest ], ); return ` ${ guest } : confirmed` ; }
Enter fullscreen mode
Exit fullscreen mode
Every line is correct. It passes the tests you'd write for it. And if ten guests try to book the same room for the same night at the same moment, all ten are confirmed.
The bug isn't in any single line. It's in the gap between two of them.…