Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | 1x 1x 1x 1x 1x 1x 1x 1x 12x 9x 3x 1x 2x 1x 1x 1x 1x 1x 3x 3x 3x 3x 9x 9x 9x 9x 9x 3x 1x 1x 1x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /*!
* mux-fetch.js v0.0.1-alpha.15
* (c) 2018-2019 空鱼
* Released under the MIT License.
*/
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var muxLib = require('mux-lib');
var defaultFetch = _interopDefault(require('isomorphic-fetch'));
/**
* 默认配置
*/
const DEFAULT_CONFIG = {
prefix: "",
fetchOption: {},
responseHandle: async res => {
const data = await res.response.clone().json();
return { ...data,
...res.options
};
},
interceptor: {
requestInterceptor: [],
responseInterceptor: [],
errorInterceptor: []
}
};
/**
* 请求类型
*/
const JSON_TYPE = "application/json";
const FORM_DATA_TYPE = "multipart/form-data;";
/**
* 匹配http,https
*/
const URL_HTTP_REG = /^http(s?)\:\/\//;
function compose(...funcs) {
if (funcs.length === 0) {
return muxLib.returnSelf;
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce((a, b) => (...args) => b(a(...args)));
}
// 处理get的JSON数据
const normalizeParams = (obj, prefix = "?") => Object.entries(obj).reduce((p, [key, value]) => `${p}${key}=${encodeURIComponent(value ? value : "")}&`, prefix); // 处理formData的数据
const normalizeFormDataParams = params => {
const myFormData = new FormData();
Object.keys(params).forEach(key => {
myFormData.append(key, params[key]);
});
return myFormData;
}; // 生成一个get的url
const normalize = (url, params = {}, prefix) => {
return url + normalizeParams(params, prefix);
};
const checkGlobalConfig = config => {
// prefix 只能为 undefined 和 string
if (config.prefix !== undefined) {
muxLib.invariant(muxLib.isString(config.prefix), `[fetch] prefix should be string , but got ${typeof config.prefix}`);
} // fetchOption 只能为 undefined 和 object
if (config.fetchOption) {
muxLib.invariant(muxLib.isPlainObject(config.fetchOption), `[fetch] fetchOption should be plain object , but got ${typeof config.fetchOption}`);
} // responseHandle 只能为 undefined 和 function
if (config.responseHandle) {
muxLib.invariant(muxLib.isFunction(config.responseHandle), `[fetch] responseHandle should be function , but got ${typeof config.prefix}`);
} // interceptor 只能为 undefined 和 object
if (config.interceptor) {
muxLib.invariant(muxLib.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]) {
muxLib.invariant(muxLib.isArray(config.interceptor[key]), `[fetch] each interceptor should be array , but got ${typeof config.interceptor[key]}`);
config.interceptor[key].forEach(v => {
muxLib.invariant(muxLib.isFunction(v), `[fetch] each interceptor should be Array<Function> , but got ${typeof v}`);
});
}
});
}
};
const configFactory = (config, base) => {
// 合并 prefix
const prefix = config.prefix || base.prefix || DEFAULT_CONFIG.prefix; // 合并 responseHandle
const responseHandle = config.responseHandle || base.responseHandle || DEFAULT_CONFIG.responseHandle; // 合并 fetchOption
const fetchOption = Object.assign({}, DEFAULT_CONFIG.fetchOption, base.fetchOption || {}, config.fetchOption || {}); // 合并 interceptor
const interceptor = Object.keys(DEFAULT_CONFIG.interceptor).reduce((p, key) => {
const configInterceptor = (config.interceptor || {})[key] || [];
const baseInterceptor = (base.interceptor || {})[key] || [];
const defaultInterceptor = DEFAULT_CONFIG.interceptor[key] || [];
p[key] = compose(...defaultInterceptor, ...baseInterceptor, ...configInterceptor);
return p;
}, {});
return {
prefix,
fetchOption,
responseHandle,
interceptor
};
};
const globalConfig = new Map();
globalConfig.set("config", configFactory({}, DEFAULT_CONFIG));
const setGlobalConfig = config => {
/**
* 开始前,进行必要的检查
*/
checkGlobalConfig(config);
/**
* 对参数进行处理
*/
const params = configFactory(config, globalConfig.get("config"));
globalConfig.set("config", params);
};
/**
* 默认加上请求方法,第二个参数约定为请求参数
*/
const fastFetchFactory = (fetch, opts) => (api, params = {}, ...args) => fetch(api, {
body: params || {},
...opts
}, ...args);
/**
* 默认的配置项
*/
const createDefaultConfig = () => globalConfig.get("config");
const fetchWebapi = async (api, opts, getConfig = createDefaultConfig) => {
/**
* getConfig 必须在运行时调用,才能保证获取的配置是最新的
* @returns interceptor
* @returns prefix
* @returns fetchOption
*/
const {
interceptor,
prefix,
fetchOption,
responseHandle
} = getConfig();
const {
requestInterceptor,
responseInterceptor,
errorInterceptor
} = interceptor;
let url, options, startTime, endTime;
try {
/**
* 请求拦截器
*/
const request = requestInterceptor({
api: URL_HTTP_REG.test(api) ? api : `${prefix}${api}`,
options: Object.assign({}, fetchOption, opts)
});
url = request.api;
options = request.options;
/**
* 如果没有,默认使用fetch
* 要求必须是返回promise的方法
*/
const fetch = options.fetch || defaultFetch;
/**
* 打印请求开始时间
*/
startTime = Date.now();
const response = await fetch(url, options);
/**
* 打印请求结束时间
*/
endTime = Date.now();
/**
* 返回响应拦截器的值
*
* @example
* const responseInterceptor = res =>res.clone().json()
*
*/
const res = await responseHandle({
response,
options: {
startTime,
endTime
}
});
return responseInterceptor(res);
} catch (error) {
errorInterceptor({
error,
options: {
type: "fetch",
url,
args: {
options,
startTime,
endTime
}
}
});
}
}; // 快捷方法
fetchWebapi.get = fastFetchFactory(fetchWebapi, {
method: "GET"
});
fetchWebapi.post = fastFetchFactory(fetchWebapi, {
method: "POST"
});
fetchWebapi.put = fastFetchFactory(fetchWebapi, {
method: "PUT"
});
fetchWebapi.delete = fastFetchFactory(fetchWebapi, {
method: "DELETE"
});
fetchWebapi.upload = fastFetchFactory(fetchWebapi, {
method: "POST",
headersType: FORM_DATA_TYPE
});
exports.DEFAULT_CONFIG = DEFAULT_CONFIG;
exports.FORM_DATA_TYPE = FORM_DATA_TYPE;
exports.JSON_TYPE = JSON_TYPE;
exports.URL_HTTP_REG = URL_HTTP_REG;
exports.checkGlobalConfig = checkGlobalConfig;
exports.compose = compose;
exports.config = globalConfig;
exports.configFactory = configFactory;
exports.fastFetchFactory = fastFetchFactory;
exports.fetchWebapi = fetchWebapi;
exports.normalize = normalize;
exports.normalizeFormDataParams = normalizeFormDataParams;
exports.normalizeParams = normalizeParams;
exports.setGlobalConfig = setGlobalConfig;
|