index.js 692 B

12345678910111213141516171819202122232425
  1. // src/middleware/timeout/index.ts
  2. import { HTTPException } from "../../http-exception.js";
  3. var defaultTimeoutException = new HTTPException(504, {
  4. message: "Gateway Timeout"
  5. });
  6. var timeout = (duration, exception = defaultTimeoutException) => {
  7. return async function timeout2(context, next) {
  8. let timer;
  9. const timeoutPromise = new Promise((_, reject) => {
  10. timer = setTimeout(() => {
  11. reject(typeof exception === "function" ? exception(context) : exception);
  12. }, duration);
  13. });
  14. try {
  15. await Promise.race([next(), timeoutPromise]);
  16. } finally {
  17. if (timer !== void 0) {
  18. clearTimeout(timer);
  19. }
  20. }
  21. };
  22. };
  23. export {
  24. timeout
  25. };