all files / utils/ paramsSerializer.js

86.67% Statements 13/15
75% Branches 6/8
100% Functions 3/3
86.67% Lines 13/15
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                14×                                                            
import types from './type';
/**
 * URL中参数编码
 *
 * @param {String} val 待编码的参数
 * @return {String} 编码后的参数
 */
function encode(val) {
	return encodeURIComponent(val)
		.replace(/%40/gi, '@')
		.replace(/%3A/gi, ':')
		.replace(/%24/g, '$')
		.replace(/%2C/gi, ',')
		.replace(/%20/g, '+')
		.replace(/%5B/gi, '[')
		.replace(/%5D/gi, ']');
}
/**
 * 序列化参数
 *
 * @param {Object} data  URL参数对象
 * @return {String} 序列化后的参数字符串
 */
function paramsSerializer(data) {
	let parmas = [];
 
	if (types.isURLSearchParams(data)) {
		return data.toString();
	}
 
	if (types.isObject(data)) {
		Object.entries(data).forEach(arr => {
			let key = arr[0],
				value = arr[1];
 
			Iif (types.isDate(value)) {
				value = value.toISOString();
			}
			Iif (types.isObject(value)) {
				value = JSON.stringify(value);
			}
			parmas.push(encode(key) + '=' + encode(value));
		});
		return parmas.join('&');
	}
 
	return data;
}
 
export default paramsSerializer;