mux-fetch
Version:
69 lines (60 loc) • 1.6 kB
text/typescript
import { fetchWebapi, fastFetchFactory } from "./fetch";
import { FORM_DATA_TYPE } from "./constant";
import blockConfigMap from "./blockConfig";
import { GlobalConfig } from "./@types/";
import { invariant, isString } from "mux-lib";
export const fetch = (...args) => {
let namespace, api, options;
if (!args.length) {
invariant(false, "[fetch] fetch need one argument at least");
}
/**
* 第一种,简单的调用接口
* @example
* fetch(api)
*/
if (args.length === 1) {
api = args[0];
options = {};
}
/**
* 第二种,调用接口带参数
* @example
* 1. fetch(api,options)
* 2. fetch(namespace,api)
* */
if (args.length === 2) {
if (isString(args[1])) {
namespace = args[0];
api = args[1];
} else {
api = args[0];
options = args[1];
}
}
/**
* 第三种,调用接口加上区块的参数
* @example
* fetch(namespace,api,options)
*/
if (args.length === 3) {
namespace = args[0];
api = args[1];
options = args[2];
}
if (!namespace) {
return fetchWebapi(api, options);
} else {
const getConfig = (): GlobalConfig => blockConfigMap.get(namespace);
return fetchWebapi(api, options, getConfig);
}
};
// 快捷方法
fetch.get = fastFetchFactory(fetch, { method: "GET" });
fetch.post = fastFetchFactory(fetch, { method: "POST" });
fetch.put = fastFetchFactory(fetch, { method: "PUT" });
fetch.delete = fastFetchFactory(fetch, { method: "DELETE" });
fetch.upload = fastFetchFactory(fetch, {
method: "POST",
headersType: FORM_DATA_TYPE
});