Handling Duplicate Requests in Express Middleware with Async/Await
I'm maintaining legacy code that I'm collaborating on a project where I'm converting an old project and I'm relatively new to this, so bear with me. After trying multiple solutions online, I still can't figure this out... Hey everyone, I'm running into an issue that's driving me crazy. I'm currently building an API using Express 4.17 and I'm working with an scenario with handling duplicate requests that might occur when users rapidly click a button to make a network request. I have a middleware function that processes incoming requests, but when the same request is sent multiple times in a short period, it seems to be causing unintentional duplicates in the database. Here's the middleware I'm using: ```javascript app.use(async (req, res, next) => { try { const existingRequest = await RequestModel.findOne({ userId: req.body.userId, status: 'pending' }); if (existingRequest) { return res.status(409).json({ message: 'Duplicate request detected' }); } next(); } catch (behavior) { console.behavior('Middleware behavior:', behavior); res.status(500).json({ message: 'Internal Server behavior' }); } }); ``` The scenario arises mainly when multiple requests are processed quickly, which occasionally leads to the creation of duplicate records despite the check. I have tried implementing debouncing on the client side using lodash's `_.debounce`, but it doesn't seem to fully solve the question. Additionally, I ensured that the `userId` is unique for each request in the database schema. Could the question be due to how promises are resolved in the middleware? Are there any better approaches to ensure that duplicate requests are effectively managed in real-time? Any insights would be greatly appreciated! What's the best practice here? I'm working on a service that needs to handle this. What's the best practice here? I'm working with Javascript in a Docker container on Debian. Am I missing something obvious? The stack includes Javascript and several other technologies. Could someone point me to the right documentation? Thanks in advance! I recently upgraded to Javascript latest. Thanks in advance!