import { Request, Response, NextFunction, RequestHandler } from "express";
import promiseMiddleware from "../../helper/promiseMiddleware.js";

type RH = (req: Request, res: Response, next?: NextFunction) => any;

function call(handler: RH, req: Request, res: Response) {
   return new Promise<void>((yes, no) => {
      let p = handler(req, res, (err) => {
         if (err) no(err);
         else yes();
      });
      if (p && p.catch) p.catch((err) => no(err));
   });
}

const Stacker = (...handler: RH[]) => {
   return promiseMiddleware(
      async (req: Request, res: Response, next: NextFunction) => {
         let hc = handler.concat();
         while (hc.length > 0) {
            let h = hc.shift();
            await call(h, req, res);
         }
         next();
      }
   );
};
export default Stacker;
