因此,我最近try 创建一个预订网站,您可以在其中 Select 您希望预订的日期.然后向/api/v1/reserve发送请求,判断数据是否有效.生成条带支付意图,将预订保存到数据库,并将支付意图id发送到前端(用于确认).我的问题是,如果两个客户同时单击"发送",他们都会为不应该发生的相同日期付款.
router.post("/reservation", async (req, res) => {
//Check if everything is in the reqest
if (!req.body?.name || !req.body?.phone || !req.body?.date) return res.sendStatus(400);
if (!req.body.phone.match(/^[+]{0,1}[4]{1,2}[8][\s0-9]*$/)) return res.status(400).json({
type: ErrorTypes.PHONE
});
//Validating date
const reservationDate = new Date(req.body.date);
if (reservationDate < new Date()) return res.status(400).json({
type: ErrorTypes.DATE
});
//Checking if date is already reserved
if (await checkIfDateReserved(reservationDate)) return res.status(400).json({
type: ErrorTypes.RESERVED
})
//if reservation date is weekend raise the price ????
const estimatedPrice = reservationDate.getDay() == 6 || reservationDate.getDay() == 0 ? 3500 : 2000;
try {
//Create payment intet
const intent = await stripe.paymentIntents.create({
amount: estimatedPrice,
currency: "PLN",
payment_method_types: ['card']
});
const document = new ReservationModel({
name: req.body.name,
reservationDate: reservationDate,
phone: req.body.phone,
complete: false,
intentId: intent.id
});
await document.save();
//If everything went smoothley, send the secret to the client
//Send the client the intent secret to confirm the payment
res.json({ clientSecret: intent.client_secret });
} catch (error) {
res.status(500);
}
});
基本上,这两个进程在不同的线程中并行运行,它们判断日期是否同时保留,并同时保留.如何使数据库在处理另一个保存请求之前等待第一个保存请求完成?reservationDate字段是唯一的,但MongoDB似乎仍然忽略了它.
另外,我也想过使用事务处理,但我真的不知道它们在这里如何apply.