import {
  invariant,
  isPlainObject,
  isString,
  isArray,
  isFunction
} from "mux-lib";

export const checkGlobalConfig = config => {
  // prefix 只能为 undefined 和 string

  if (config.prefix !== undefined) {
    invariant(
      isString(config.prefix),
      `[fetch] prefix should be string , but got ${typeof config.prefix}`
    );
  }

  // fetchOption 只能为 undefined 和 object

  if (config.fetchOption) {
    invariant(
      isPlainObject(config.fetchOption),
      `[fetch] fetchOption should be plain object , but got ${typeof config.fetchOption}`
    );
  }

  // responseHandle 只能为 undefined 和 function

  if (config.responseHandle) {
    invariant(
      isFunction(config.responseHandle),
      `[fetch] responseHandle should be function , but got ${typeof config.prefix}`
    );
  }

  // interceptor 只能为 undefined 和 object

  if (config.interceptor) {
    invariant(
      isPlainObject(config.interceptor),
      `[fetch] interceptor should be plain object , but got ${typeof config.interceptor}`
    );

    // 每一种的 interceptor 只能为 undefined 和 Array<Function>

    Object.keys(config.interceptor).forEach(key => {
      if (config.interceptor[key]) {
        invariant(
          isArray(config.interceptor[key]),
          `[fetch] each interceptor should be array , but got ${typeof config
            .interceptor[key]}`
        );

        config.interceptor[key].forEach(v => {
          invariant(
            isFunction(v),
            `[fetch] each interceptor should be Array<Function> , but got ${typeof v}`
          );
        });
      }
    });
  }
};
