import { Interceptor } from "./types";

/**
 * 复合拦截器
 * @example compose((request, next) => {}, (request, next) => {})
 */
export function compose(...interceptors: Interceptor[]): Interceptor {
  return (request, next) => {
    const combined = (index: number): ReturnType<Interceptor> => {
      if (index === interceptors.length) {
        // 结尾
        return next();
      } else {
        const interceptor = interceptors[index];
        return interceptor(request, () => combined(index + 1));
      }
    };

    return combined(0);
  };
}
