compose.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // src/compose.ts
  2. var compose = (middleware, onError, onNotFound) => {
  3. return (context, next) => {
  4. let index = -1;
  5. return dispatch(0);
  6. async function dispatch(i) {
  7. if (i <= index) {
  8. throw new Error("next() called multiple times");
  9. }
  10. index = i;
  11. let res;
  12. let isError = false;
  13. let handler;
  14. if (middleware[i]) {
  15. handler = middleware[i][0][0];
  16. context.req.routeIndex = i;
  17. } else {
  18. handler = i === middleware.length && next || void 0;
  19. }
  20. if (handler) {
  21. try {
  22. res = await handler(context, () => dispatch(i + 1));
  23. } catch (err) {
  24. if (err instanceof Error && onError) {
  25. context.error = err;
  26. res = await onError(err, context);
  27. isError = true;
  28. } else {
  29. throw err;
  30. }
  31. }
  32. } else {
  33. if (context.finalized === false && onNotFound) {
  34. res = await onNotFound(context);
  35. }
  36. }
  37. if (res && (context.finalized === false || isError)) {
  38. context.res = res;
  39. }
  40. return context;
  41. }
  42. };
  43. };
  44. export {
  45. compose
  46. };