bunrest icon indicating copy to clipboard operation
bunrest copied to clipboard

Async middleware not working correctly

Open filipduch opened this issue 7 months ago • 2 comments

When using async middleware it starts the execution and jumps right back to the next one before it finishes.

import server from "bunrest";
const app = server();
const port = 3000;

const asyncMiddleware = async (req, res, next) => {
  console.log(new Date(), "start");
  await Bun.sleep(2000);
  console.log(new Date(), "end");
  res.status(429).send("Too many requests");
};

app.get("/user", asyncMiddleware, (req, res) => {
  console.log(new Date(), "user endpoint");
  res.status(200).json({ message: "ok" });
});

app.listen(port, () => {
  console.log(`App is listening on port ${port}`);
});`

Output:

App is listening on port 3000
2023-11-09T18:54:44.563Z start
2023-11-09T18:54:44.563Z user endpoint
2023-11-09T18:54:46.563Z end
284 |         if (
285 |           typeof target[prop] === "function" &&
286 |           (prop === "json" || prop === "send") &&
287 |           target.isReady()
288 |         ) {
289 |           throw new Error("You cannot send response twice");
                    ^
error: You cannot send response twice
      at get (.../node_modules/bunrest/src/server/server.ts:289:16)

Expected output (processing should end when middleware sends 429):

App is listening on port 3000
2023-11-09T18:54:44.563Z start
2023-11-09T18:54:46.563Z end

Other Relevant Info: Bun version: v1.0.2 bunrest version: v1.3.7 platform: ubuntu 20.04 node installed: yes node version: v18.12.0

filipduch avatar Nov 09 '23 19:11 filipduch